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

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

问题描述

我有一些这样的 html:

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

还有一些像这样的JS:

$("button").click(function () {var buttonNo = $(this).attr('class');var正确 = Number($(this).attr('rel'));验证(数字($(#"+buttonNo+输入").val()),正确);$("#"+buttonNo+" div").html(反馈);});

我真正想要的是,如果我不必在按钮上设置 class="1"(我知道数字类无效,但这是一个 WIP!),这样我就可以确定 buttonNo基于父div的id.在现实生活中,有多个部分是这样的.

  1. 如何找到作为按钮父级的 div 的 ID.

  2. 在按钮代码中存储答案的更语义方式是什么.我想让这对于非程序员来说尽可能万无一失,可以在不破坏东西的情况下进行复制和粘贴!

解决方案

你可以使用事件委托 在父 div 上.或者使用 closest 方法来查找按钮的父级.

两者中最简单的可能是最接近的.

var id = $("button").closest("div").prop("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天全站免登陆