如何获得换行符

时间:2016-12-18 13:13:40

标签: jquery html

我一直在尝试在触发更改事件时复制另一个div中复选框旁边的内容。我几乎已经完成了这个,但是我无法在另一个div中获得换行符。这是我的代码:

这是我要从

复制的div
<div>
    <input  type="checkbox"/><label for="1">One</label><br>
    <input  type="checkbox"/><label for="2">Two</label><br>
    <input  type="checkbox"/><label for="3">Three</label><br>
    <input  type="checkbox"/><label for="4">Four</label><br>
</div>

这是我要复制的div

<div id="myDiv"></div>

我的jquery代码是:

$(":checkbox").change(function() {
            var arr = $(":checkbox:checked").map(function() { 
            return $(this).next().text(); 
            }).get();
            $("#myDiv").text(arr.join(' '));
          });

此外,如果有任何替代方法可以完成整个jquery代码,我肯定想知道。

谢谢。

2 个答案:

答案 0 :(得分:1)

具体的情况下,您只需将text更改为html并在<br>电话中使用join(但请继续阅读) :

$(":checkbox").change(function() {
    var arr = $(":checkbox:checked").map(function() { 
        return $(this).next().text(); 
    }).get();
    $("#myDiv").html(arr.join('<br>'));
    // ---------^^^^-----------^^^^
});

只有在您的复选框标签文字中没有<&时才有效;如果确实如此,那将是有问题的。

更强大的解决方案会抓取标签的HTML而不是文本,以便正确处理任何<&

$(":checkbox").change(function() {
    var arr = $(":checkbox:checked").map(function() { 
        return $(this).next().html();
    // -----------------------^^^^
    }).get();
    $("#myDiv").html(arr.join('<br>'));
    // ---------^^^^-----------^^^^
});

实例,改变标签以证明逃避(以及两个&#34;侧面注释&#34;来自我对所提问题的评论):

&#13;
&#13;
$(":checkbox").change(function() {
    var arr = $(":checkbox:checked").map(function() { 
        return $(this).next().html();
    }).get();
    $("#myDiv").html(arr.join('<br>'));
});
&#13;
<div>
    <input id="c1" type="checkbox"/><label for="c1">&lt;One></label><br>
    <input id="c2" type="checkbox"/><label for="c2">&lt;Two></label><br>
    <input id="c3" type="checkbox"/><label for="c3">&lt;Three></label><br>
    <input id="c4" type="checkbox"/><label for="c4">&lt;Four></label><br>
</div>
<div id="myDiv"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你应该这样做:

$("#myDiv").html(arr.join('<br>'));

这是example

使用.text()函数将转义特殊字符,但是 .html()功能赢了