【问题标题】:Function not working for innerhtml功能不适用于 innerhtml
【发布时间】:2015-10-29 18:12:20
【问题描述】:

我有一个功能可以在 div 类“关闭”的单击时移动一些 div。这最初工作得很好,但我用 output.innerHTML 编辑了这些 div 的内容,当我这样做时,脚本不再在点击时工作。

Javascript:

$(function()
{
       var open = true;
       $('.close').click(function() {
            if (open = true)
            {
                $("#upper").animate({'top' : '0px'}, {duration : 400});
                open = true;

                $("#lower").animate({'top' : '0px'}, {duration : 400});
                open = true;

                $("#filler").animate({'top' : '0px'}, {duration : 400});
                open = true;
            }
            else {
            }
       }); 
});

还有:

function enable() {
  var output = document.getElementById("passwordinfo");
  var sentence = '<h4>RE-ENABLE HMS MEDHOST ACCOUNT</h4>' + 
         '<div class="close" onclick="close()"></div>';
  var open = true;
  output.innerHTML = sentence;
}

“enable”函数在 div 中输入 html 很好,但是 .close 的 onclick 不再起作用。任何想法我在这里缺少什么?

【问题讨论】:

  • 只是为了确保您只有 #upper、#lower 和 #filler 中的一个,对吗? ID 是唯一的,如果有多个当前的 JS 会选择(我想说它看到的第一个,但它可能是最后一个)。也失去了你的jQuery在类上运行的onClick,无论如何它是无关紧要的,以后可能会造成混淆。此外,您正在检查 open 是否为 true,然后将 open 设置为 true,我假设您的意思是在关闭 div 后将其设置为 false。最后 open = true 是 SETTING 打开。你想要 if(open==true) 或者只是 if(open)

标签: javascript html css


【解决方案1】:

在启用功能中可以重新添加点击事件:

function enable() {
var output = document.getElementById("passwordinfo");
var sentence = '<h4>RE-ENABLE HMS MEDHOST ACCOUNT</h4><div class="close" onclick="close()"></div>';
var open = true;
output.innerHTML = sentence;
$('.close').off('click')
$('.close').click(function()
    {
        ....
        ....
        ....
        ....
    }
}

我可能不起作用,因为您在添加点击事件后添加了一个 html。不要忘记使用 .off('click'),否则当你第一次添加事件时,对于已经在 dom 中的元素,该事件会触发两次

【讨论】:

    【解决方案2】:

    您应该使用.on.live 在DOM 中动态添加元素。 if 条件也是错误的。

    试试这个:

    $(function()
    {
           var open = true;
           $(document).on("click", ".close", function() {
                if (open)
                {
                    $("#upper").animate({'top' : '0px'}, {duration : 400});
                    open = true;
    
                    $("#lower").animate({'top' : '0px'}, {duration : 400});
                    open = true;
    
                    $("#filler").animate({'top' : '0px'}, {duration : 400});
                    open = true;
                }
                else {
                }
           }); 
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-27
      • 2013-08-05
      • 2014-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-12
      • 1970-01-01
      相关资源
      最近更新 更多