jQuery的innerHTML和.html()之间的区别 [英] Difference between innerHTML and .html() from jQuery
问题描述
有人可以说出jquery .html()函数和innerHTML有什么区别吗?
<script type="text/javascript">
$(document).ready(function(){
$('#test_link').click(function(){
//$('#div_test_out').html("<div width='250px' height='100px' id='div_test'><script language='javascript'>alert('insider');<\/script>asddsa</div>");
document.getElementById('div_test_out').innerHTML="<div width='250px' height='100px' id='div_test'><script language='javascript'>alert('insider');<\/script>asddsa</div>";
});
});
</script>
<a href="#" id="test_link" >TEST LINK :-)</a><br/><br/>
<div width="100px" height="100px" id="div_test_out"></div>
当我使用第一个选项(即jQuery)时,脚本会在内部运行,并显示警报,但是如果我使用第二个选项时,innerHTML(虽然我是相同的,但两者之间没有区别)不起作用;-(
可能是什么原因?
jQuery的.html()方法是用于访问和操纵innerHTML的多功能函数.当用作设置器时,它返回用于链接的jQuery集合.当用作吸气剂时,它将返回集合元素内部的标记表示形式.
当您将其用作设置器时(将标记写入元素中),jQuery会读取标记并从内部提取脚本.然后,将它们以导致其执行的方式分别添加到DOM中. .html()隐式地导致一些操作(脚本处理为一个),而写入innerHTML只会导致innerHTML发生更改,但对该HTML所做的工作很少.
Can somebody tell what is the difference between jquery .html() function and innerHTML?
<script type="text/javascript">
$(document).ready(function(){
$('#test_link').click(function(){
//$('#div_test_out').html("<div width='250px' height='100px' id='div_test'><script language='javascript'>alert('insider');<\/script>asddsa</div>");
document.getElementById('div_test_out').innerHTML="<div width='250px' height='100px' id='div_test'><script language='javascript'>alert('insider');<\/script>asddsa</div>";
});
});
</script>
<a href="#" id="test_link" >TEST LINK :-)</a><br/><br/>
<div width="100px" height="100px" id="div_test_out"></div>
When I use first option, that is jQuery, script inside runs, and alert shows up, but if I use second option that with the innerHTML (which I though is the same and there is no difference between them), script is not working ;-(
What could be the cause?
jQuery's .html() method is a multipurpose function for accessing and manipulating innerHTML. When used as a setter, it returns the jQuery collection for chaining. When used as a getter, it returns the markup representation of the collection elements' innards.
When you use it as a setter--to write markup into an element--jQuery reads the markup and extracts scripts from within. It then adds them to the DOM separately in a manner that causes their execution. .html() implicitly causes a few operations (script handling being one) whereas writing to innerHTML simply causes the innerHTML to change, but very little is done with that HTML.
这篇关于jQuery的innerHTML和.html()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!