问题
<div id="element_id">hellow world</div>
var value = $('#element_id').html()
returns the "hello world"
sometimes, but not always. val()
always works, but not html()
This only happens in firefox (always works in Chrome). Any ideas?
EDIT Still haven't figured out the problem yet, but I will post the conclusion once I have found it! Thanks for the responses.
回答1:
I think this previous question might help you.
P.S. When you say it is sometime working and sometime not working, are there some changes going on the div's content ?
回答2:
You could try wrapping it into a timeout...
function sayHello() {
var someContent = $('#element_id').html();
alert(someContent);
}
setTimeout('sayHello()', 500);
See if it's getting the content far too early?
回答3:
This worked using jQuery 1.4.4. I haven`t tested with other versions.
$(document).ready(function(){
function showhtml() {
var eid = $('div.eid').html();
alert(eid);
$('code.status').html(eid);
}
showhtml();
});
Remembering that .text will return only the text inside the div and .html will return the text surrounded by the html tags.
回答4:
The complete unaltered code for you to try:
<!doctype html>
<html lang="pt-br">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style type="text/css">
p {color:#4f4}
code {color:#999;font-family:monospace;font-size:14px}
</style>
<script type="text/javascript" src="libraries/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function showhtml(n) {
//1 for html 0 for text
if(n == 1) {
var eid = $('div.eid').html();
alert(eid);
$('code.status').html(eid);
} else if(n == 0 || n == null) {
var eid = $('div.eid').text();
alert(eid);
$('code.status').text(eid);
}
}
showhtml();
});
</script>
<title>jQuery html() text()</title>
</head>
<body>
<div class="eid">
<p>1 ajfdlk jaldkfjdksljfkldjlfkjal;fd</p>
<em>2 ajd;fjal;kdjf</em>
</div>
<br />
<hr />
<code class="status"></code>
</body>
</html>
来源:https://stackoverflow.com/questions/4835621/jquery-issue-with-firefox-element-id-html-not-working