Jquery find() 不适用于两个 ID,其中一个具有另一个的子字符串

Jquery find() not working with two ids one having the substring of the other

我有HTML这样的代码

<div id="city-parrent">
<input id="london" type="checkbox" value="London" name="c_city_2">
<input id="london_r" type="checkbox" value="London" name="c_city_r_2">
</div>

当我想select第一个复选框用

var object_found = $("#city-parrent").find("#london");
alert(object_found.val());

它给出了一个未定义的警报

当我 select 使用相同代码的第二个时,它不会给出未定义的警报

var object_found = $("#city-parrent").find("#london_r");
alert(object_found.val());

通常这段代码没问题,但我将这段代码放在出现此问题的 for 循环中。这是for循环 [查看for循环]]1

应该可以正常工作。你有什么版本的Jquery? 你的版本应该可以工作,有时,你可能必须用 jquery 包装它。 $(object_found).val().

检查这个,它有效。

https://jsfiddle.net/atg5m6ym/5585/

我没有发现你的代码有任何问题:JSFIDDLE

尝试将您的代码附在:

    $(document).ready(function(){
you code is here
});

Loop 通过 array 并检查元素是否存在。这将防止您出错。不需要 .find() for id 只需使用普通选择器 $('#id') 因为 id 那里只有一个,否则你会得到第一个。

var array_cont = ['london', 'london_r']
array_cont.map(function(ac) {
    $elem = $('#' + ac);
    if ($elem.length) {
        alert($elem.val());
        $elem.attr('checked', true);
    }
})

var array_cont = ['london', 'london_r']
array_cont.map(function(ac) {
  $elem = $('#' + ac);
  if ($elem.length) {
    alert($elem.val());
    $elem.attr('checked', true);
  }
})
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<div id="city-parrent">
  <input id="london" type="checkbox" value="London" name="c_city_2">
  <input id="london_r" type="checkbox" value="London2" name="c_city_r_2">
</div>