这是我的html标记:
<a onclick="cart.add('10');" class="product-10">Add to cart</a>
<a onclick="cart.add('11');" class="product-11">Add to cart</a>
<a onclick="cart.add('12');" class="product-12">Add to cart</a>这是我的javascript对象:
var cart = {
'add': function(product_id) {
//What I want console.log(element_that_was_clicked.attr('class'));
}
}是否有一种无需编辑html标记就可以检测哪个a调用cart.add的方法?
更新
a标记没有class,我添加这些类只是为了演示,实际上我需要a对象本身,因为我想访问它的下一个兄弟,我的标记如下所示:
<div><a onclick="cart.add('10');">Add to cart</a><input type="text" name="quantity" /></div>我想:
var cart = {
'add': function(product_id) {
//What I want console.log(element_that_was_clicked.next().val());
}
}发布于 2018-03-09 07:21:58
首先,删除内联onclick (这是不好的做法)并注册一个事件侦听器:
<a id="10" class="product-10">Add to cart</a>jQuery
$(document).on('click', 'a', function() {
var product_id = $(this).attr('id'); // Or any other attribute
cart.add(product_id);
});编辑
基本上,通过执行removeInlineHandlers,您可以删除内联onclick属性,并分配一个调用传递单击元素的add函数的事件处理程序:
function removeInlineHandlers() {
$('a').each(function() {
var that = $(this);
var thisId = that.attr('onclick').match(/\d+/);
that.removeAttr('onclick')
.on('click', function() {
cart.add(thisId, that);
});
})
}
var cart = {
'add': function(product_id, elem) {
alert('Added id: ' + product_id + ' with quantity of: ' + elem.next('input').val());
}
}
removeInlineHandlers();<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a onclick="cart.add('10');">Add to cart</a><input type="text" name="quantity" />
<a onclick="cart.add('11');">Add to cart</a><input type="text" name="quantity" />
<a onclick="cart.add('12');">Add to cart</a><input type="text" name="quantity" />
发布于 2018-03-09 07:24:47
最好或理想的方法是使用jQuery事件侦听器。就我个人而言,我会找到一种改变HTML的方法。
但是,如果真的不能更改,则可以使用onclick属性作为选择器。这是个糟糕的练习。
类似于:
var cart = {
'add': function(product_id) {
//$("[onclick=\"cart.add('" + product_id + "');\"]") <-- Getting the clicked a using onclick attribute
$("[onclick=\"cart.add('" + product_id + "');\"]").next().val("TEST");
}
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div><a onclick="cart.add('10');">Add to cart</a><input type="text" name="quantity" /></div>
<div><a onclick="cart.add('11');">Add to cart</a><input type="text" name="quantity" /></div>
<div><a onclick="cart.add('12');">Add to cart</a><input type="text" name="quantity" /></div>
理想的做法是使用类添加事件侦听器。比如:
$(function(){
$(".product").click(function(){
$(this).next().val("TEST");
});
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div><a class="product">Add to cart</a><input type="text" name="quantity" /></div>
<div><a class="product">Add to cart</a><input type="text" name="quantity" /></div>
<div><a class="product">Add to cart</a><input type="text" name="quantity" /></div>
https://stackoverflow.com/questions/49188494
复制相似问题