我有以下HTML
<div id="example">
...some text...
<script type="text/javascript">
... some javascript...
</script>
</div>
如何获取#example
的内容以及JavaScript的内容?
$("#example").html(),
$("#example").text(),
$("#example").val()
一切都行不通。
答案 0 :(得分:11)
html()
方法适合您。在DOM完成后,您确定要运行代码吗?
$(document).ready(function(){
alert($("#example").html());
});
答案 1 :(得分:5)
答案 2 :(得分:1)
只需使用:
$("#example").get().innerHTML;
从jQuery对象获取DOM对象并吐出原始内容。
答案 3 :(得分:1)
var txt = document.getElementById("example").innerHTML;
这将获取div的innertext。在身体标签的末尾写下这一行。 要么 在一个将在 body onLoad
之后调用的方法中调用它答案 4 :(得分:0)
试过它和$('#example')。html()确实是孤立的:
<html>
<head>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js' lang='text/javascript' />
</head>
<body>
<div id="example">
...some text...
<script type="text/javascript">
... some javascript...
</script>
</div>
<script>
alert($('#example').html());
</script>
</body>
</html>
答案 5 :(得分:0)
<!--This code will work -->
<html>
<head>
<!--<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" lang='text/javascript' />-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
//alert($('#example p').html());
alert($('#example').text());
alert($('#example #1').text());
alert($('#example #2').text());
alert($('#example #3').text());
alert($('#example #4').text());
//alert($("#example p").get().innerHTML);
//alert('hey');
});
</script>
</head>
<body>
<div id="example">
<p>...some text...</p>
<div id="1">
Here's 1
</div>
<div id="2">
Here's 2
</div>
<div id="3">
Here's 3
</div>
<div id="4">
Here's 4
</div>
</div>
</body>
</html>
答案 6 :(得分:0)
menuItem.firstChild.innerHTML
也许这有帮助。
答案 7 :(得分:0)
这对我有用: $( “#例子”)。内容()
答案 8 :(得分:0)
在我的情况下,我从Web服务获取一个html片段(作为JSON返回的对象中的属性)。我想显示它没有格式化,也没有javascript块。 .html()
会为我返回javascript块,因此无效。
我最终得到的是:
// Build up the message a bit artificially for this demo.
// is actually response from ajax call
var message = '<scri';
message += 'pt type="text/javascript">var foo = "bar";</scr'
message += 'ipt><h2>A heading</h2><div>This is a message</div>';
var message_html = jQuery('<div/>') // create a container
.html(message) // set the contents from the message
.find('script') // find script blocks
.remove() // and remove them
.end(); // back to the original collection but without script blocks
// Now get just the text from there
alert(message_html.text());