Ric*_*haw 99 jquery dom semantics
我有一些像这样的HTML:
<div id="1">
<p>
Volume = <input type="text" />
<button rel="3.93e-6" class="1" type="button">Check answer</button>
</p>
<div></div>
</div>
Run Code Online (Sandbox Code Playgroud)
和一些JS这样:
$("button").click(function () {
var buttonNo = $(this).attr('class');
var correct = Number($(this).attr('rel'));
validate (Number($("#"+buttonNo+" input").val()),correct);
$("#"+buttonNo+" div").html(feedback);
});
Run Code Online (Sandbox Code Playgroud)
我真正喜欢的是如果我没有按钮上的class ="1"(我知道数字类无效,但这是一个WIP!),所以我可以确定buttonNo基于父div的id.在现实生活中,有多个部分看起来像这样.
如何找到按钮的div的id.
在按钮代码中存储答案的更加语义的方法是什么.我希望尽可能让非程序员在不破坏东西的情况下进行复制和粘贴!
Mar*_*ark 211
您可以在父div上使用事件委派.或者使用最近的方法查找按钮的父级.
两者中最简单的可能是最接近的.
var id = $("button").closest("div").prop("id");
Run Code Online (Sandbox Code Playgroud)
Rob*_*ant 48
1.
$(this).parent().attr("id");
Run Code Online (Sandbox Code Playgroud)
2.
必须有很多方法!一个可能是隐藏包含答案的元素,例如
<div>
Volume = <input type="text" />
<button type="button">Check answer</button>
<span style="display: hidden">3.93e-6</span>
<div></div>
</div>
Run Code Online (Sandbox Code Playgroud)
然后有类似的jQuery代码到上面抓住:
$("button").click(function ()
{
var correct = Number($(this).parent().children("span").text());
validate ($(this).siblings("input").val(),correct);
$(this).siblings("div").html(feedback);
});
Run Code Online (Sandbox Code Playgroud)
请记住,如果您将答案放在客户端代码中,那么他们可以看到它:)最好的方法是在服务器端验证它,但对于范围有限的应用程序,这可能不是问题.
Buu*_*yen 11
试试这个:
$("button").click(function () {
$(this).parents("div:first").html(...);
});
Run Code Online (Sandbox Code Playgroud)
要获取父div的id:
$(buttonSelector).parents('div:eq(0)').attr('id');
Run Code Online (Sandbox Code Playgroud)
此外,您可以相当多地重构您的代码:
$('button').click( function() {
var correct = Number($(this).attr('rel'));
validate(Number($(this).siblings('input').val()), correct);
$(this).parents('div:eq(0)').html(feedback);
});
Run Code Online (Sandbox Code Playgroud)
现在不需要按钮类
解释
eq(0),意味着您将从jQuery对象中选择一个元素,在本例中为元素0,因此是第一个元素.http://docs.jquery.com/Selectors/eq#index
$(selector).siblings(siblingsSelector)将选择与siblingsSelector http://docs.jquery.com/Traversing匹配的所有兄弟(具有相同父元素的元素)/ siblings
#exp $(selector).parents(parentsSelector)将选择与父选择器匹配的选择器匹配的元素的所有父项.http://docs.jquery.com/Traversing/parents#expr
因此:$(selector).parents('div:eq(0)'); 将匹配选择器匹配的元素的第一个父div.
你应该看看jQuery文档,特别是选择器和遍历:
http://jsfiddle.net/qVGwh/6/ 检查一下
$("#MadonwebTest").click(function () {
var id = $("#MadonwebTest").closest("div").attr("id");
alert(id);
});
Run Code Online (Sandbox Code Playgroud)
小智 5
这可以通过以下方式轻松完成:
$(this).closest('table').attr('id');
Run Code Online (Sandbox Code Playgroud)
将它附加到表中的任何对象,它将返回该表的id.