声明性地为HTML链接设置jQuery.Data属性

时间:2011-09-27 04:40:58

标签: javascript jquery asp.net repeater declarative

假设我在数据网格或转发器中的行中有HTML链接

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

现在也假设我已经在jQuery中处理了所有我的DoSomethings的click事件

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

将数据传递给依赖于所点击链接的点击事件的正确技巧是什么?

如果没有jQuery,你通常会做这样的事情。

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

但这种技术显然不适用于jQuery案例。

基本上我理想的解决方案会以某种方式为点击链接的jQuery.Data属性添加值,但是以声明方式这样做。

3 个答案:

答案 0 :(得分:4)

使用HTML5数据属性。 jQuery支持内置于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'));
 });

答案 1 :(得分:2)

您可以使用attr()函数。

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

});

答案 2 :(得分:2)

我的问题不清楚,但可能会有所帮助

$(".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"
});
相关问题