.innerHTML not working or am I using it wrong?
If I understand right, .innerHTML should overwrite whatever was in a certain div or span. For example:
<table width="90%" border="0" align="center" cellpadding="5" cellspacing="0">
<tr>
<td colspan="2" align="left">Via Email:</td>
<td width="1070" align="right"></td>
</tr>
<script>
$('#addEmail').click(function() {
document.getElementById('emailList').innerHTML = "12345";
});
</script>
<span id="emailList">
<tr>
<td width="27" align="left"><img src="icon_mail.png" width="24" height="24"></td>
<td width="228" align="left">123obama@whitehouse.com</td>
<td align="right"><a href="#" id="dialog_link" class="ui-state-default ui-corner-all"><span class="ui-icon ui-icon-close"></span>remove</a></td>
</tr>
</span>
<tr>
<td colspan="3" align="left"><br>
<input name="input4" type="text" value="vova@kremlin.ru" size="20">
<a href="#" id="addEmail" class="ui-state-default ui-co开发者_开发知识库rner-all"><span class="ui-icon ui-icon-mail-closed"></span>Add Email</a></td>
</tr>
</table>
Therefor upon click of #addEmail button, everything inside would be removed and replaced by "12345".
Yet in reality it doesn't do anything to that span, but just prints out 12345 in the place, where the script is.
Any ideas what could be wrong?
The HTML is invalid — you can't wrap a <tr>
in a <span>
. The browser is performing error recovery on your code and producing a DOM that isn't what you expect it to be. When you try to edit the content of the span, the span probably isn't where you think it is.
… you can't put a script between table rows either.
… and you are trying to bind an event handler to a link before the link exists in the document. You either need to move the script so it appears after the link, or move the code that does the work into an event handler that runs after the link exists (such as the ready
event).
It's actually your span
that's wrong. A span can't ... span (I know, I know) over table rows, so it gets opened and closed somewhere between the rows (or outside the table on some browsers), so when you're overwriting it's html, it ends up somewhere else.
You should name the tr
instead and overwrite its html, that should work.
You can't put a <tr>
inside a <span>
like that. Anyway if you're using jQuery, you should probably use its API around ".innerHTML"
$('#emailList').html("hello world");
That will do some important cleanup work for you. It's not absolutely required, but unless you know for sure what you're doing it's probably a safer option.
You are wrapping a <tr>
in a span. That is going to lead to unpredictable results. Especially if you then remove the table row.
精彩评论