简体   繁体   中英

Declaratively setting jQuery.Data property for a HTML link

Assuming I have a HTML link in my rows inside a datagrid or repeater as such

<a href="javascript:void(0);" class="DoSomething">DoSomething</a>

Now also assuming that I have handled the click event for all my DoSomethings in jQuery as such

$(".DoSomething").click(function (e) {
    //Make my DoSomethings do something
});

What is the correct technique for passing data to the click event that is dependent on the link clicked?

Without jQuery you would typically do something like this.

<a href="javascript:void(0);" class="DoSomething" onclick="DoSomething('<%# Eval("SomeValue") %>');">DoSomething</a>

but this technique obviously doesn't work in the jQuery case.

Basically my ideal solution would somehow add values for to the jQuery.Data property for the link clicked but doing so declaratively.

Use HTML5 data- attributes. jQuery support is built-in for 1.4.3+

http://api.jquery.com/data/#data2

 <a href="#" class="product-link" data-productid="77">click here</a>

 $('.product-link').click(function (e) {
     alert($(this).data('productid'));
 });

You could use the attr() function.

http://api.jquery.com/attr/

$("#Something").attr("your-value", "Hello World");

$("#Something").click(function (e) {
    //Make my DoSomethings do something
   var value = $(this).attr("your-value");
   alert(value); // Alerts Hello World

});

your question was not clear to me but may be this will help

$(".DoSomething").click(function (e) {
    //Make my DoSomethings do something
    $(this).data("key","value");
    //later the value can be retrieved like
    var value=$(this).data("key");
    console.log(value);// gives you "value"
});

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