简单改变innerHTML不起作用

时间:2014-02-08 01:53:14

标签: javascript

我有这段代码,我想点击<span>中的链接然后应该改变这个<span>的innerHTML。

<span id="button_report_<?php echo $row->id ?>_spam"><a class="btn red btn-xs" onlick="changeSpamButton<?php echo $row->id ?>()" target="report_iframe_<?php echo $row->id ?>" href="resource/report.php?id=<?php echo $row->id ?>&ttype=currency&type=spam">Spam</a></span>
<span id="button_report_<?php echo $row->id ?>_na"><a class="btn yellow btn-xs" onlick="changeNAButton<?php echo $row->id ?>()" target="report_iframe_<?php echo $row->id ?>" href="resource/report.php?id=<?php echo $row->id ?>&ttype=currency&type=na">Unavailability</a></span>
<script type="text/javascript">
function changeSpamButton<?php echo $row->id ?>() {
    document.getElementById("button_report_<?php echo $row->id ?>_spam").innerHTML = '<a class="btn default btn-xs">Spam</a>';
}

function changeNAButton<?php echo $row->id ?>() {
    document.getElementById("button_report_<?php echo $row->id ?>_na").innerHTML = '<a class="btn default btn-xs">Unavailability</a>';
}
</script>

非常感谢任何帮助。谢谢!

1 个答案:

答案 0 :(得分:0)

正如我所说,您必须将onlick更改为onclick。但是为了让您了解如何简化事件处理:

<span data-type="spam">
    <a onclick="changeButton(this.parentNode)">Spam</a>
</span>
<span data-type="na">
    <a onclick="changeButton(this.parentNode)">Unavailability</a>
</span>

<script type="text/javascript">
var content = {
    'spam': '<a class="btn default btn-xs">Spam</a>',
    'na': '<a class="btn default btn-xs">Unavailability</a>'
};

function changeButton(element) {
   element.innerHTML = content[element.getAttribute('data-type')];
}
</script>

这使您的代码更易于阅读,理解和维护。

阅读材料:Introduction to event handling - quirksmode.org