使用Jquery查找父div的id [英] Finding the id of a parent div using Jquery

查看:321
本文介绍了使用Jquery查找父div的id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些这样的html:

 < div id =1> 
< p>
Volume =< input type =text/>
< button rel =3.93e-6class =1type =button>检查答案< / button>
< / p>
< div>< / div>
< / div>

和一些这样的JS:

 $(button)。click(function(){
var buttonNo = $(this).attr('class');
var correct = Number $(this).attr('rel'));

validate(Number($(#+ buttonNo +input)。val()),正确);
$ (#+ buttonNo +div)。html(feedback);
});

我真的很喜欢的是,如果我不必让class =1在按钮上(我知道数字类是无效的,但这是一个WIP!),所以我可以根据父div的id来确定buttonNo。在现实生活中,有多个部分看起来像这样。


  1. 如何找到父母的按钮ID。 / p>


  2. 在按钮代码中存储答案的更为语义的方法是什么?我想让这个尽可能地防止非程式员复制和粘贴,而不会破坏东西!



解决方案

您可以在父div上使用事件委托。或者使用最接近的方法来查找按钮的父级。



最简单的两个可能是最接近的。

  var id = $(button) 。.closest( DIV)丙( ID); 


I have some html like this:

<div id="1">
    <p>
        Volume = <input type="text" />
        <button rel="3.93e-6" class="1" type="button">Check answer</button>
    </p>
    <div></div>
</div>

and some JS like this:

$("button").click(function () {
    var buttonNo = $(this).attr('class');
    var correct = Number($(this).attr('rel'));

    validate (Number($("#"+buttonNo+" input").val()),correct);
    $("#"+buttonNo+" div").html(feedback);
});

What I'd really like is if I didn't have to have the class="1" on the button (I know numeric classes aren't valid, but this is a WIP!), so I could determine buttonNo based on the id of the parent div. In real life there are multiple sections looking like this.

  1. How do I find the id of the div parenting the button.

  2. What would be a more semantic way to store the answer in the button code. I want to make this as foolproof as possible for a non programmer to copy and paste without breaking things!

解决方案

You could use event delegation on the parent div. Or use the closest method to find the parent of the button.

The easiest of the two is probably the closest.

var id = $("button").closest("div").prop("id");

这篇关于使用Jquery查找父div的id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆