简体   繁体   中英

How to fire on onclick event on clicking on an anchor text

I would like to fire an onclick event using Javascript whenever an user clicks on "Remoe Item". Given below is the actual code available. The problem is I do not see any id, class to identify the click on this anchor text. Any idea how to do that?

<a href="javascript:removeCartItem('ci6223000698')">Remove Item</a>

Thanks in advance.

Roy

You can attach the Click Event using this selector [href="#"] and set an attribute data-value .

Run this code snippet:

 var removeCartItem = function(value) { console.log(`You're about to remove this item: ${value}`); }; var anchors = document.querySelectorAll('[href="#"]'); for (a of anchors) { a.addEventListener('click', function(e) { removeCartItem(e.target.getAttribute('data-value')); }); } 
 <a href="#" data-value='ci6223000698'>Remove Item</a> <a href="#" data-value='ci6223000677'>Remove Item</a> 

See? the value was printed from your function removeCartItem .

Bonus with jQuery

Using the .data() looks fancier.

Store arbitrary data associated with the matched elements or return the value at the named data store for the first element in the set of matched elements.

Run this code snippet:

 var removeCartItem = function(value) { console.log(`You're about to remove this item: ${value}`); }; $('[href="#"]').click(function() { removeCartItem($(this).data('value')); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="#" data-value='ci6223000698'>Remove Item</a> <a href="#" data-value='ci6223000677'>Remove Item</a> 

you need to add an EventHandler :

<a href="#" id="remove" onclick="myFunction('ci6223000698')">Remove Item</a>

while you'd need to have a function like this:

function myFunction(myVar) { //... }

or if you prefer adding the handler js side:

document.getElementById('remove').addEventListener("click", function() {
  // your stuff
})

or with jQuery:

$('#remove').click(function() { //.... })

example in fiddle:

https://jsfiddle.net/txy5tyg2/1/

further reading:

addEventListener vs onclick

https://www.w3schools.com/js/js_htmldom_eventlistener.asp

You can retrieve all tag and add an event listener.

you can find the examples here, How to add click event to an element?

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