使用data()访问元素?

时间:2011-12-29 04:22:03

标签: javascript jquery css-selectors

我无法更改ID,我无法更改名称,我需要两个不同的类来设置元素的样式。

可以使用data()访问元素吗?基本上,我如何访问data-arrow="el"

  $(".vote").data("arrow");
  $(".vote").click(function () {//here i need a selector that should have a permanent name

  //some code
  });

<a href="" class="vote" id="<?php echo $id ?>" name="up" data-arrow="el">up</a>
<a href="" class="vote" id="<?php echo $id ?>" name="down" data-arrow="el">down</a>

感谢

2 个答案:

答案 0 :(得分:4)

$("a.vote[data-arrow='el']").click(function(){
    alert("clicked");
});

Example

这是jQuery的attribute equals selector

但是,选择课程a的所有vote元素会不会更好?像这样:

$("a.vote").click(function(){...});

此外,建议使用on()进行事件处理:

$(document).on("click", "a.vote[data-arrow='el']", function(e){
    e.preventDefault();
    alert("clicked");
});

Example

答案 1 :(得分:1)

如果您尝试从点击处理程序中访问被点击的元素的数据,您可以这样做:

$(".vote").click(function () {
    var arrow = $(this).data("arrow");
    // do whatever you want with the value of the arrow variable
});

如果您正在尝试使用数据箭头值创建选择器,您可以(如Purmou的帖子中所示),但是添加另一个类并在选择器中使用它会更加清晰: / p>

<a href="" class="vote el" id="<?php echo $id ?>" name="up">up</a>

和jQuery选择器只选择那些元素:

$(".vote.el")
相关问题