首页 > 解决方案 > 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());
    }); 
});

标签: jquerysiblingsclosest

解决方案


由于多个相同的 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>

推荐阅读