2017-03-12 55 views
1

我在HTML中的按钮,单击时,我需要它的索引属性值传递给我的点击收听:如何将数据传递给我的点击收听

<button class="btn buy-button js-prevent-cart-listener guys" index="1">Add To Cart</button> 

和听众:

$('.girls').on('click', buyButtonGirlsClickHandler, index); 

所以,当我运行这个功能,我可以访问事件值和函数中使用它:

function buyButtonClickHandler(evt) { 
    console.log(evt.value); 
    } 

我不想将其更改为在该按钮上附加“onclick()”。这是可能的,如果是这样的话?显然上面的代码不能通过索引值,我已经尝试了很多次

+1

'var index = this.getAttribute(“index”)' – Andreas

回答

1

你不需要在on函数中传递索引。你应该尝试的功能,改变你对

$('.girls').on('click', buyButtonGirlsClickHandler); 

并在处理程序可以通过attr

function buyButtonClickHandler(evt) { 
    console.log(evt.value); 
    var index= $(event.target).attr("index"); 
    } 

https://jsfiddle.net/525npjfn/

收到或@Andreas评论,请使用这里面点击。

function buyButtonGirlsClickHandler(evt) { 
    console.log(evt.value); 
     var index = this.getAttribute("index"); 
     alert(index); 
    } 

https://jsfiddle.net/525npjfn/2/

0

在点击按钮,你可以存储在一个变量,它的索引值,然后将其传递到所需要的功能。这是解决您的问题的干净片段。

请使用data-前缀来使用自定义HTML属性,否则HTML验证器会为此哭。

$(document).ready(function() { 
 
    $('.js-prevent-cart-listener').click(function() { 
 
    var idx = $(this).attr('data-index'); 
 
    buyButtonClickHandler(idx); 
 
    }) 
 
}); 
 

 
function buyButtonClickHandler(idx) { 
 
    console.log("This is index value " + idx); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button class="btn buy-button js-prevent-cart-listener guys" data-index="1">Add To Cart</button>

0

而不是直接传递的事件处理程序,它包装到一个新的函数内部。您的索引数据将被传递,因为它保持在范围内。

let index = "whatever your index data is"; 
$('.girls').on('click', (e, index) => buyButtonGirlsClickHandler(e, index)); 

注:我在那里使用ES6语法,可能无法在旧版浏览器上运行。

+0

索引是被点击的按钮的属性 – Andreas

相关问题