Jquery - 创建一个div和其他子元素

时间:2022-11-18 17:26:46

I'm trying to make a comment section for my site. After a comment has been posted I would like to show it immediately instead of being forced to reload the page. So I need to somehow be able to create div and other elements and later fill them with the relevant data.

我正在尝试为我的网站制作评论部分。评论发布后,我想立即显示,而不是*重新加载页面。所以我需要以某种方式能够创建div和其他元素,然后用相关数据填充它们。

$(document).ready(function () {

    $(".commentAnswer").keypress(function (e) {
        if (e.which == 13) {

            var commentData = { Value: ($(input).attr("data-answerId")),
                Description: ($(input).attr("value"))
            };

            $.ajax({
                type: "POST",
                url: '@Url.Action("SubmitComment", "Home")',
                data: JSON.stringify(commentData),
                dataType: "json",
                contentType: 'application/json, charset=utf-8',
                traditional: true,
                success: function (data) {
                    //create elements.

                }
            });

        }

    });

This the block I want to create.

这是我想要创建的块。

<div class="commentContent">
     <div class="comment">@comment.Comment.Text</div>
     <ul>
         <li>
             <div class="newsTime">@comment.User.FirstName @comment.User.LastName</div>
         </li>
         <li>- </li>
         <li>
             <div class="newsTime">
                 @foreach (var role in comment.CommenterRoles) {
                     if (role.Role.Equals("Authenticated") || role.Role.Equals("Administrator")) {
                                            //Don't write anything
                     } else {
                         @role.Role@:.
                     }
                 }
             </div>
         </li>
         <li>- </li>
         <li>
             <div class="newsTime">
                 @Project.Tools.TimeTool.ToTimeSinceString(comment.Comment.SubmitDateTime)
             </div>
        </li>
    </ul>
</div>
<hr />

4 个解决方案

#1


4  

This is a very basic example of how to add comment dynamically. Whitout more information on what data is returned I cant help much more. This makes the assumption that your Action returns a partial view for that single comment.

这是如何动态添加注释的一个非常基本的示例。关于返回什么数据的更多信息,我无法提供更多帮助。这假设您的Action返回该单个注释的部分视图。

JSFiddle containing example markup: http://jsfiddle.net/HenryGarle/SMbxk/

JSFiddle包含示例标记:http://jsfiddle.net/HenryGarle/SMbxk/

// This is what you would add to your success call - Assumes that your action method returns a parial view for the comment


data = "<div class=\"comment\"> Some Example </div>";

$(".commentContent").prepend(data);

My recomendations:

我的推荐:

Create a partial view that displays a single comment. Inside of your comments do a foreach loop calling the partial passing through a single comment object. i.e:

创建显示单个注释的部分视图。在你的注释内部做一个foreach循环调用部分传递单个注释对象。即:

foreach (var comment in Model.Comments)
{
 @Html.Partial("comment", comment);
}

Comment.cshtml:

Comment.cshtml:

This is where you place your repeated mark up.

这是您重复标记的位置。

SubmitComment action: Return the partial Comment.cshtml with the newly added Comment

SubmitComment操作:使用新添加的Comment返回部分Comment.cshtml

return View("Comment", newCommentObj);

This means there will be no extra data being passed around. The other approach is to take the information posted in and add the markup yourself using the prepend (Or append, depending on your needs) Or as nayish has mentioned, use the clone but again although this is a little more manual and you'll end up managing the markup in two places instead of one. Using these methods would make maintaining it a pain in the long run.

这意味着不会传递额外的数据。另一种方法是获取发布的信息并使用前置添加标记(或者根据您的需要添加)或者正如nayish所提到的那样,使用克隆但是再次使用克隆,尽管这是一个更多的手册,你将结束在两个地方而不是一个地方管理标记。使用这些方法会使其长期保持痛苦。

#2


4  

What you need to do is create an area in your page which is hidden and there put any elements you want to multiply and change later:

你需要做的是在你的页面中创建一个隐藏的区域,并放置你想要的任何元素并在以后更改:

HTML

HTML

<div id="hidden" style="display: none">
     <div class="commentContent">
          <div class="comment">@comment.Comment.Text</div>
          <ul>
              <li>
                  <div class="newsTime"></div>
              </li>
              <li>- </li>
              <li>
                   <div class="newsTime">
                   </div>
              </li>
              <li>- </li>
              <li>
                  <div class="newsTime">
                  </div>
             </li>
        </ul>
    </div>
</div>

now using jquery clone this div and change the inside of the different list items and plant it wherever you want on the page.

现在使用jquery克隆这个div并更改不同列表项的内部并将其植入到页面上的任何位置。

#3


3  

Use the .load() function to load the results of an ajax call to a selector.

使用.load()函数将ajax调用的结果加载到选择器。

If you aim it at an action that returns partial view then you won't have to play with the JSON result to build the HTML to insert into the DOM using the DOM insertion functions:

如果您将其瞄准返回部分视图的操作,那么您将不必使用JSON结果来构建HTML以使用DOM插入函数插入到DOM中:

#4


2  

You may want to have a look a this: http://api.jquery.com/jquery.tmpl/

你可能想看看这个:http://api.jquery.com/jquery.tmpl/

I think it's still beta, but it made me think about your question.

我认为它仍然是测试版,但它让我思考你的问题。

#1


4  

This is a very basic example of how to add comment dynamically. Whitout more information on what data is returned I cant help much more. This makes the assumption that your Action returns a partial view for that single comment.

这是如何动态添加注释的一个非常基本的示例。关于返回什么数据的更多信息,我无法提供更多帮助。这假设您的Action返回该单个注释的部分视图。

JSFiddle containing example markup: http://jsfiddle.net/HenryGarle/SMbxk/

JSFiddle包含示例标记:http://jsfiddle.net/HenryGarle/SMbxk/

// This is what you would add to your success call - Assumes that your action method returns a parial view for the comment


data = "<div class=\"comment\"> Some Example </div>";

$(".commentContent").prepend(data);

My recomendations:

我的推荐:

Create a partial view that displays a single comment. Inside of your comments do a foreach loop calling the partial passing through a single comment object. i.e:

创建显示单个注释的部分视图。在你的注释内部做一个foreach循环调用部分传递单个注释对象。即:

foreach (var comment in Model.Comments)
{
 @Html.Partial("comment", comment);
}

Comment.cshtml:

Comment.cshtml:

This is where you place your repeated mark up.

这是您重复标记的位置。

SubmitComment action: Return the partial Comment.cshtml with the newly added Comment

SubmitComment操作:使用新添加的Comment返回部分Comment.cshtml

return View("Comment", newCommentObj);

This means there will be no extra data being passed around. The other approach is to take the information posted in and add the markup yourself using the prepend (Or append, depending on your needs) Or as nayish has mentioned, use the clone but again although this is a little more manual and you'll end up managing the markup in two places instead of one. Using these methods would make maintaining it a pain in the long run.

这意味着不会传递额外的数据。另一种方法是获取发布的信息并使用前置添加标记(或者根据您的需要添加)或者正如nayish所提到的那样,使用克隆但是再次使用克隆,尽管这是一个更多的手册,你将结束在两个地方而不是一个地方管理标记。使用这些方法会使其长期保持痛苦。

#2


4  

What you need to do is create an area in your page which is hidden and there put any elements you want to multiply and change later:

你需要做的是在你的页面中创建一个隐藏的区域,并放置你想要的任何元素并在以后更改:

HTML

HTML

<div id="hidden" style="display: none">
     <div class="commentContent">
          <div class="comment">@comment.Comment.Text</div>
          <ul>
              <li>
                  <div class="newsTime"></div>
              </li>
              <li>- </li>
              <li>
                   <div class="newsTime">
                   </div>
              </li>
              <li>- </li>
              <li>
                  <div class="newsTime">
                  </div>
             </li>
        </ul>
    </div>
</div>

now using jquery clone this div and change the inside of the different list items and plant it wherever you want on the page.

现在使用jquery克隆这个div并更改不同列表项的内部并将其植入到页面上的任何位置。

#3


3  

Use the .load() function to load the results of an ajax call to a selector.

使用.load()函数将ajax调用的结果加载到选择器。

If you aim it at an action that returns partial view then you won't have to play with the JSON result to build the HTML to insert into the DOM using the DOM insertion functions:

如果您将其瞄准返回部分视图的操作,那么您将不必使用JSON结果来构建HTML以使用DOM插入函数插入到DOM中:

#4


2  

You may want to have a look a this: http://api.jquery.com/jquery.tmpl/

你可能想看看这个:http://api.jquery.com/jquery.tmpl/

I think it's still beta, but it made me think about your question.

我认为它仍然是测试版,但它让我思考你的问题。