jquery - jQuery getting closest html when I have to use the same IDs for forms
问题描述
Firstly I know I shouldn't have the same IDs, but in this case it unavoidable ... I am trying to click a button that will take the .html()
of a div
and add that text to an input field. Problem is that everything has the same IDs and there will be an unknown number of them. Example is:
<div id="Product">
<div id="Product-stats"><div class="builder-name">Example Builder</div></div>
<form><input id="abc" value=-""></input></form>
<a href="#" class="cart-get-quote-button"></a>
<div>
<div id="Product">
<div id="Product-stats"><div class="builder-name">Another Builder</div></div>
<form><input id="abc" value=-""></input></form>
<a href="#" class="cart-get-quote-button"></a>
<div>
<div id="Product">
<div id="Product-stats"><div class="builder-name">Third Builder</div></div>
<form><input id="abc" value=-""></input></form>
<a href="#" class="cart-get-quote-button"></a>
<div>
So I need to click each link and have the builder-name content copied to the relative input value, obviously I can get this to work with just one set, but not multiple, so I though maybe trying to use sibling? or closest? This is what I have that does not work
$(document).ready(function() {
$('.cart-get-quote-button').on('click', function() {
$(this).closest('input[id="abc"]').val($(this).closest('.builder-name').html());
});
});
解决方案
由于多个相同的 id 在 HTML 中是非法的,因此它们将不起作用,并且您根本无法在 JS 中使用它们。无论您尝试什么解决方案,都必须完全忽略 ID。
工作 JSFiddle(我已经修复了您的 HTML 中的其他几个错误)。这有效:
var text = $(this).closest('div').find('.builder-name').text();
$(this).closest('div').find('input').val(text);
请注意,您的 HTML 中还有其他几个错误,在您修复它们之前,没有任何 JS 可以工作。他们可能只是这里的错别字:
- 输入中的连字符
... value=-"">
应该是... value="">
; - 收盘
Product
</div>
其实是一个新的开盘<div>
; - 你不需要
</input>
;
推荐阅读
- reactjs - “AnyReactComponent”有什么作用?
- django - 如何用 Django 和 Celery 记录所有任务信息?
- lua - Mouse cylinder behaviour (dual-screen config)
- javascript - 如何在迭代到下一个循环之前等待每个内部完成?
- node.js - 如何在 NodeJS 服务器上使用 mongoose 同步查询
- javascript - Importing JavaScript files in Typescript, unable to access functions in TS, able to access them in html
- dart - Flutter 返回首页
- c# - ASP.Net Core: keep windows authentication
- java - JVM G1 FinalReference 很多时间
- python - 检查多个字符串是否连续存在于另一个字符串中