簡體   English   中英

調用 function onClick 並將元素的 data-* 屬性中的值傳遞給它

[英]Call a function onClick and passing it a value from the element's data-* attribute

我有這樣的鏈接:

<li><a href="#" data-value="Codes">Get codes</a></li>
<li><a href="#" data-value="Product">Get products</a></li>

我怎樣才能做到這一點,以便在我單擊鏈接時調用 function 來傳遞數據值中包含的值?

function refreshGrid(value) { }

嘗試以下操作:

$('li > a[href="#"][data-value]').click(function (e) { // On click of all anchors with a data-value attribute and a href of # that are immediate children of li elements (nb this selector can be modifed to suit your needs)
  e.preventDefault(); // prevent the default (navigate to href)
  refreshGrid($(this).data('value')); // call your refreshGrid function with the value contained in the 'data-value' attribute
});
var linkValue = $("li a").attr("data-value");

編輯:更好的例子

$("li a").click(function () {
    var myDataValue = $(this).attr("data-value");
    refreshGrid(myDataValue);
});

這是一個快速示例

$('ul').on('click','a[data-value]',function(){
    refreshGrid(this.getAttribute('data-value'));
    return false;
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM