使用jQuery选择数据id
使用jQuery,当用户单击其中一个按钮时,我希望能够从单选按钮中选择数据评级使用jQuery选择数据id,jquery,html,Jquery,Html,使用jQuery,当用户单击其中一个按钮时,我希望能够从单选按钮中选择数据评级 <label class="ratingStar"><input type="radio" name="spotRating" id="_1of5" data-rating="1" data-spot-id="1" class="rating-system" /></label> <label class="ratingStar"><input type="rad
<label class="ratingStar"><input type="radio" name="spotRating" id="_1of5" data-rating="1" data-spot-id="1" class="rating-system" /></label>
<label class="ratingStar"><input type="radio" name="spotRating" id="_1of5" data-rating="2" data-spot-id="2" class="rating-system" /></label>
试试这个,元素中没有id,所以我猜您指的是数据点id
$(".ratingStar").on("click", function(){
selected_rating = $('input', this).data("rating");
selected_id = $('input', this).data("spot-id"); //Changed to spot-id
console.log(selected_rating)
});
以下各项将起作用:
$(".ratingStar").on("click", function () {
selected_rating = $('input', $(this)).data("rating");
selected_id = $('input', $(this)).data("spot-id");
console.log(selected_rating)
});
编辑1:如果我们将$this
修改为this
或$(this)
,实际上它甚至可以处理数据(“id”)
例如,下面的方法很有效。点击查看演示
$(".ratingStar").on("click", function () {
selected_rating = $('input', this).data("rating");
selected_id = $('input', this).data("id"); // data("spot-id") also works
console.log(selected_rating)
});
编辑2:引用安东尼·格里斯特的评论
上下文(即第二个参数)可以是DOM元素或
jQuery对象此
是一个DOM元素,因此您可以直接传递它:
$('input',this)
。执行$(this)
调用jQuery函数,并创建
一个新的jQuery对象只包含这个-因为您不需要这样做
这样做(通过这个很好)你应该避免这样做
基于上述情况,在编辑1下提供的答案是首选选项。您可以使用
你已经告诉我们你尝试了什么,现在告诉我们有什么问题。它有什么作用?为什么这不正确?它实际上应该做什么?您的两个按钮具有相同的id,这是无效的html。
$this
未定义。这就是你的代码不起作用的全部原因。如果您转到控制台,这一点应该非常清楚,除非您有其他类似的功能,您没有使用可能设置了全局$this
的var
关键字。绝对没有理由这样做$(this)
(至少有几个理由不这样做).请给我解释一下,以便我能理解并停止使用。我想这也会给答案增加更多的价值。旁注,它在fiddle$this
中只能以这种方式工作。上下文(第二个参数)可以是DOM元素或jQuery对象此
是一个DOM元素,因此您可以直接传递它:$('input',this)
。执行$(this)
调用jQuery函数,并创建一个新的jQuery对象,该对象只包含this
——因为您不需要这样做(传递this
效果很好),所以您应该避免这样做。@AnthonyGrist:谢谢。我将把它更新为答案。
$(".ratingStar").on("click", function () {
selected_rating = $('input', this).data("rating");
selected_id = $('input', this).data("id"); // data("spot-id") also works
console.log(selected_rating)
});
$(".ratingStar").on("click", function(){
selected_rating = $('input', $this).attr("data-rating");
selected_id = $('input', $this).attr("data-spot-id");
console.log(selected_rating);
});