简体   繁体   English

单击锚文本时如何触发onclick事件

[英]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". 我想在用户单击“远程项目”时使用Javascript触发onclick事件。 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. 问题是我看不到任何ID,类来标识对此锚文本的单击。 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 . 您可以使用此选择器[href="#"]附加点击事件,并设置属性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 . 该值是从函数removeCartItem打印出来的。

Bonus with jQuery jQuery奖励

Using the .data() looks fancier. 使用.data()看起来更好。

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 : 您需要添加一个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: 或者,如果您喜欢添加处理程序js端:

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

or with jQuery: 或使用jQuery:

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

example in fiddle: 摆弄的例子:

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

further reading: 进一步阅读:

addEventListener vs onclick addEventListener与onclick

https://www.w3schools.com/js/js_htmldom_eventlistener.asp 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? 您可以在此处找到示例, 如何将click事件添加到元素?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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