代码之家  ›  专栏  ›  技术社区  ›  Jason

JavaScript动态onClick问题

  •  0
  • Jason  · 技术社区  · 15 年前

    下面是我尝试过的。

    document.getElementById(subDiv).onclick = function() { alert('Error. There is an error on the the page. Please correct that then submit the page'); };
    
    
    document.getElementById(subDiv).onclick = "alert('Error. There is an error on the the page. Please correct that then submit the page');";
    
    
    function redErrorAlert()
    {
        alert('Error. There is an error on the the page. Please correct that then submit the page');
    }
    document.getElementById(subDiv).onclick = redErrorAlert;
    
    
    
    document.getElementById(subDiv).setAttribute('onclick',redErrorAlert(), false);
    
    
    
    document.getElementById(subDiv).setAttribute('onclick','redErrorAlert()', false);
    

    4 回复  |  直到 15 年前
        1
  •  0
  •   virstulte    15 年前

    这听起来像jQuery领域。一旦您了解了jQuery的来龙去脉,像这样的事情就很容易处理了,您会发现自己编写的JavaScript要少得多。

    首先,从 http://jquery.com/

    然后将其放入代码中以绑定事件:

    $('#idOfElementToBindClickEvent').click(function(){
      alert('Error.');
    });
    

    jQuery基本上提供了一种使用类似CSS的选择器来操作元素的方法。

        2
  •  2
  •   Jacob Relkin    15 年前

    在对DOM树进行查询之前,需要等待创建DOM树。

    确保所有这些都发生在创建的上下文中 已构建DOM树:

    window.onload = function() {
        document.getElementById(subDiv).onclick = function() { alert('Error. There is an error on the the page. Please correct that then submit the page'); };
    };
    
        3
  •  1
  •   Faisal    15 年前

    (也有可能代码中的变量subDiv是一个包含ID的字符串,但是由于您没有提到它,所以我假设它没有。)

    编辑:

    $(document).ready(function() {
        $("#subDiv").click(function() { alert("Test!"); });
    });
    
        4
  •  0
  •   Kevin    15 年前

    尝试

    document.getElementById(subDiv).onclick = alert('Error. There is an error on the the page. Please correct that then submit the page');
    

    function redAlert() {
        alert('Error. There is an error on the the page. Please correct that then submit the page');
    }
    
    document.getElementById(subDiv).onclick = redAlert();
    

    第二种情况:您分配了一个函数,但没有调用此函数