简体   繁体   English

javascript关闭div追加

[英]javascript closing div append

My div is closing itself. 我的div正在关闭。

<html><head><title></title>
<script type="text/javascript" charset="utf-8" src="jquery-1.7.min.js"></script>
<script>

$(document).ready(function(){   
        $("#wrapper").append( '<div id="content"><br>test');
        $("#wrapper").append('<br>whatever');
        $("#wrapper").append( 'sfga<br></div>' );
});
</script>

</head><body>

<div id="wrapper">
</div>

</body></html>

The div is automatically closing after test is output and not after sfga like it should. 输出test后div会自动关闭,而不是像sfga那样。

How to fix this? 如何解决这个问题?

Dirty fix: 脏修复:

var sHTML = '<div ="content"><br>test<br>whateversfga<br></div>';
$("#wrapper").append(sHTML);

Proper way of doing it: 正确的做法:

var oNewDiv = $('<div id="content">').append('<br />').append('test');
$("#wrapper").append(oNewDiv);

Why this happens? 为什么会这样? Because jQuery is automatically creating proper DOM elements when given raw HTML, while letting you append to them with the above chaining. 因为jQuery在给定原始HTML时会自动创建正确的DOM元素,同时允许您通过上述链接附加到它们。

You are operating on a DOM, not a text stream. 您正在操作DOM,而不是文本流。

Despite the abstraction that jQuery provides, you can deal only with elements, not with tags. 尽管jQuery提供了抽象,但您只能处理元素,而不能处理标记。

 var html = '<div ="content"><br>test' +
            '<br>whatever') + 
            'sfga<br></div>';
 $("#wrapper").append(html);

(note that <div ="content"> is nonsense, but I have no idea what you meant by it so I haven't tried to fix it up). (注意<div ="content">是无稽之谈,但我不知道你的意思,所以我没有尝试修复它)。

Why not combine those three append calls? 为什么不结合这三个append电话?

$(document).ready(function(){   
    $("#wrapper").append( '<div ="content"><br>test<br>whateversfga<br></div>' );
});

If you need to put other things inside the div, you could create a new div and then append other elements to it, doing something like this: 如果你需要在div中放入其他东西,你可以创建一个新的div然后将其他元素附加到它,做这样的事情:

$(document).ready(function(){   
    var $newElem = $('<div class="content"></div>');
    $newElem.append($('<p>test<br />test</p>'));
    $("#wrapper").append($newElem);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM