【问题标题】:Weird bug when "innerHTML" is used..?使用“innerHTML”时出现奇怪的错误..?
【发布时间】:2020-08-30 11:17:07
【问题描述】:

我发现了一个我无法理解的奇怪错误。有人可以解释为什么下面的代码不起作用吗?当我将 Button2 放在 <div id='test'> 中时,它停止工作。

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>

<button id='button1'>Button1</button>


<div id='test'>
    <button id='button2'>Button2</button>
</div>

<script>
//Global var
var content = document.getElementById('test');

$(document).ready(function(){
    $('#button1').on('click', function(){
        content.innerHTML += '<hr>';
    });
});

$(document).ready(function(){
    $('#button2').on('click', function(){
        content.innerHTML += ' Test';
    });
});

</script>
</body>
</html>

【问题讨论】:

  • 既然你替换了按钮元素,那么事件处理程序就不再适用了
  • 尚未检查,但据我回忆,+= '&lt;hr&gt;' 确实意味着您将 innerHTML 设置为当前的 innerHTML 值,加上新的 hr 标签。这将删除任何事件侦听器。而是在该 document.ready 调用(您不需要 2 个)中执行 $('#test').on('click', '#button2', function(){...})
  • 改用$(content).append(' Test')。将保留所有其他元素的原始内容,并且不会删除事件侦听器

标签: javascript html jquery css innerhtml


【解决方案1】:

“事件”在您更改元素时不再有效。从上层元素馈入以保持在“事件”中。

 $('#button2').on('click', function(){

 replace width:

 $('body').on('click', '#button2', function () {

【讨论】:

    猜你喜欢
    • 2013-05-05
    • 2012-05-05
    • 2011-06-16
    • 1970-01-01
    • 2011-01-08
    • 2012-12-26
    • 2017-09-03
    • 2018-05-03
    • 2015-10-24
    相关资源
    最近更新 更多