我有一些类似这样的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>

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. 在按钮代码中存储答案的更具语义的方式是什么.我想让非程序员在不 destruct 东西的情况下进行复制和粘贴,尽可能做到万无一失!

推荐答案

您可以在parent div上使用event delegation,或者使用closest方法查找按钮的父级.

The easiest of the two is probably the closest.

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

Jquery相关问答推荐

JQuery日期 Select 器未设置从jQuery中 Select 的月份起90天或3个月

提交表单时运行自定义验证脚本

使用 shell 脚本判断 json 数组响应是否具有特定用户名和状态的 jq 命令

即使我使用 [FromBody] C# 从视图(Ajax)发送请求时在控制器中收到 NULL 对象

如何在 jQuery 中 Select 特定的表单元素?

在 `click` 和 `enter` 上触发事件

显示的 jQuery 日期 Select 器年份

如何使用 jQuery 显示忙碌指示器?

如何使用 jQuery UI Resizable 仅水平或垂直调整大小?

使用 D3.js(IE、safari 和 chrome)创建 SVG 后,如何保存/导出 SVG 文件?

使用 jQuery Select 最后 5 个元素

blueimp 文件上传插件中的 maxFileSize 和 acceptFileTypes 不起作用.为什么?

如何使用 requirejs 使 jQuery 插件可加载

JQuery Ajax Post 导致 500 内部服务器错误

Jquery:如何判断元素是否具有某些 css 类/样式

javascript过滤对象数组

如何插入元素作为第一个子元素?

detach()、hide() 和 remove() 之间的区别 - jQuery

如何禁用由子元素触发的 mouseout 事件?

JQuery 判断 DOM 中的重复 id