jQuery追加类

4
我正在尝试在单击事件中使用jQuery来复制此HTML。
<div class="comments_action_207">
   <div class="list_item_comments list_item_comments_207">
      <div class="comment_separator">text goes here</div>
   </div>
</div>

在点击事件之前,我有以下HTML:

<div class="comments_action_207"></div>

所以我需要将这个代码添加到之前的代码中

<div class="list_item_comments list_item_comments_207"><div class="comment_separator">text goes here</div></div>
3个回答

2
我想你可能在寻找类似于这样的内容:

我假设你正在寻找类似于这样的东西:

$(function() {
    $('.comments_action_207').click(function() {
        var num = this.className.split('_').pop();
        $('<div/>',{'class':'list_item_comments list_item_comments_' + num})
            .append('<div class="comment_separator">text goes here</div>')
            .appendTo(this);
    });
});

该点击事件特别指定为comments_action_207元素。我猜你想要将其分配给其他元素。

这将获取类名末尾的数字,创建新元素,在需要的位置添加数字,并将结果附加到comments_action_207元素。

生成的HTML将是:

<div class="comments_action_207">
    <div class="list_item_comments list_item_comments_207">
        <div class="comment_separator">text goes here</div>
    </div>
</div>

我有这个代码(不需要点击事件和num)$('<div/>',{'class':'list_item_comments list_item_comments_214'}) .append('<div class="comment_separator">test</div>') .appendTo(this); 但是它不起作用。 - Yannick
@Yannick - 你是说你不在一个点击处理程序中吗?是什么触发了这段代码?如果你不在处理程序中,但它只是在页面加载时运行,请将.appendTo(this)更改为.appendTo('.comments_action_214') - user113716

1

你想在jQuery中将要添加的HTML代码作为字符串数据类型设置为变量。然后在单击函数处理程序中,将div的HTML内容设置为该变量。在jQuery中,它看起来像这样(假设在运行此脚本之前已加载了jQuery)。

http://docs.jquery.com/Html jQuery选择器中获取和设置HTML的文档。

//jquery code:

<script type="text/javascript">
$(document).ready(function(){
    var stringToAdd = "<div class='list_item_comments list_item_comments_207'><div class='comment_separator'>text goes here</div></div>"

    $('.comments_action_207').click(function(){
       $(this).html(stringToAdd);
     });

});
</script>

通过用反引号 ` 或缩进四个空格来使代码等宽(因此易读)。不过,答案很棒! - Christian Mann
抱歉,我是 Stack Overflow 的新手,所以我只能手动缩进输入代码。 - Kobby

0
$(".comments_action_207").empty(); // clear the div off, if you do not want to retain old values

$(".comments_action_207").append("<div class='list_item_comments list_item_comments_207'><div class='comment_separator'>text goes here</div></div>");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接