Passing parameters in Javascript onClick event

前端 未结 9 973
滥情空心
滥情空心 2020-12-02 09:43

I\'m trying to pass a parameter in the onclick event. Below is a sample code:

相关标签:
9条回答
  • 2020-12-02 10:32

    It is probably better to create a dedicated function to create the link so you can avoid creating two anonymous functions. Thus:

    <div id="div"></div>
    
    <script>
      function getLink(id)
      {
        var link = document.createElement('a');
        link.setAttribute('href', '#');
        link.innerHTML = id;
        link.onclick = function()
        {
          onClickLink(id);
        };
        link.style.display = 'block';
        return link;
      }
      var div = document.getElementById('div');
      for (var i = 0; i < 10; i += 1)
      {
        div.appendChild(getLink(i.toString()));
      }
    </script>
    

    Although in both cases you end up with two functions, I just think it is better to wrap it in a function that is semantically easier to comprehend.

    0 讨论(0)
  • 2020-12-02 10:38
    link.onclick = function() { onClickLink(i+''); };
    

    Is a closure and stores a reference to the variable i, not the value that i holds when the function is created. One solution would be to wrap the contents of the for loop in a function do this:

    for (var i = 0; i < 10; i++) (function(i) {
        var link = document.createElement('a');
        link.setAttribute('href', '#');
        link.innerHTML = i + '';
        link.onclick=  function() { onClickLink(i+'');};
        div.appendChild(link);
        div.appendChild(document.createElement('BR'));
    }(i));
    
    0 讨论(0)
  • 2020-12-02 10:39

    Try this:

    <div id="div"></div>
    
    <script language="javascript" type="text/javascript">
       var div = document.getElementById('div');
    
       for (var i = 0; i < 10; i++) {
           var f = function() {
               var link = document.createElement('a');
               var j = i; // this j is scoped to our anonymous function
                          // while i is scoped outside the anonymous function,
                          //  getting incremented by the for loop
               link.setAttribute('href', '#');
               link.innerHTML = j + '';
               link.onclick=  function() { onClickLink(j+'');};
               div.appendChild(link);
               div.appendChild(document.createElement('br')); // lower case BR, please!
           }(); // call the function immediately
       }
    
       function onClickLink(text) {
           alert('Link ' + text + ' clicked');
           return false;
       }
    </script>
    
    0 讨论(0)
提交回复
热议问题