passing parameter to javascript onclick function

前端 未结 3 736
刺人心
刺人心 2021-01-28 18:40

I am having problem with getting parameter from javascript onClick function

title = \"as\"
$(\'
  • 相关标签:
    3条回答
    • 2021-01-28 19:01

      Try this way :

      hello = 'anything';
      $('<li onClick=pushRight("'+hello+'") class="item"></li>')
      
      0 讨论(0)
    • 2021-01-28 19:10
      title = "as"
      $('<li onClick="pushRight("'+hello+'")" class="item"></li>')
      

      See the added double quotes. "'+hello+'" Also double quotes over your pushRight function.

      Your code won't work because it render an invalid html as shown below.

      <li onClick=pushRight(as) class="item"></li>
      

      See, there were no quotes before and after pushRight, also before and after your string "sa". Know the mistake and correct. Using inline js with html is not recommended.You have to bind events in these scenarios.

      0 讨论(0)
    • 2021-01-28 19:13

      Please don't use inline js (onlick in your html).

      See reasons not to use inline js here: https://www.google.com/search?q=Why+is+inline+js+bad%3F

      Here's a proper way with jQuery:

      var $myElem = $('<li class="item"></li>');
      $myElem.click(function() {
        pushRight('hello');
      });
      

      And it's quite easy even without jQuery:

      var myElem = document.createElement('li');
      myElem.className = 'item';
      myElem.addEventListener('click', function() {
        pushRight('hello');
      });
      

      Live demo here: http://jsbin.com/uDURojOY/1/edit

      0 讨论(0)
    提交回复
    热议问题