简体   繁体   中英

Click on Anchor tag is not working

Click on Anchor tag is not working..Here is my code:

$('#selectall').onclick(function () {
    console.log("Hello");
});

<li>
  <a class="selectall" id="selectall">
     <i class="fa fa-square-o"></i> Select All
  </a>
</li>

Try the click event!

the problem is that "onclick" isn't supposed to used this way. You can either do

$('#selectall').click(function ....)

or

$('#selectall').on('click', function ....)

a

$('#selectall').onclick(function ... )

does not exist for jQuery. 'onclick' is by default a javascript function.

  $('#selectall').click(function () { alert("Hello"); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <li><a class="selectall" id="selectall"><i class="fa fa-square-o"></i> Select All</a></li> 

您似乎正在使用jquery,因此应使用click而不是onclick

just apply

 <a href="javascript:void(0)".... >

or

 <a href="#".... >

and use method as "click" not "onclick"

Since you also id-ed it with "selectall", the "#" is allright. You do need $('#selectall').click(function () { tho.

Also, when is your js executed? If the above js-code is executed BEFORE the html containg the anchor tag is rendered, it will fail, because there is nothing yet to bind it to.

I assume the $ is jQuery so use .click() not .onclick()

otherwise, the vanillaJS code is

document.getElementById('selectall').addEventListener('click',function(){
    console.log('hello');
},false);

I always use delegate events, so a.selectall elements can be added/removed dynamically w/out messing up your click listener.

$("body").on("click", ".selectall", function(evt){
    //click handler code here
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM