简体   繁体   English

jquery如何检查具有某个类的附近元素是否存在?

[英]jquery how to check near element with certain class exist?

I have two element inside <tr> :我在<tr>中有两个元素:

<table>
<tbody>
<tr>
   <td><input type="text" class="form-control input-state" onclick="myfunction(this)"></td>
   <td><input type="text" class="form-control input-city" onclick="myfunction(this)"></td>
</tr>
</tbody>
</table>

in the myfunction I want to check if element with cartain class exist or not:myfunction中,我想检查带有 cartain 类的元素是否存在:

if($(thisElem).closest("tr").find(".input-city").length){
    console.log('true')
 }

but $(thisElem).closest("tr").find(".input-city").length is always 0 !但是$(thisElem).closest("tr").find(".input-city").length总是0 how do I check this element existance?如何检查此元素的存在?

This is to show that the problem is due to the invalid html since tr should be wrapped inside a table like this demo shows:这是为了表明问题是由于无效的 html 造成的,因为 tr 应该像这个演示所示的那样包装在一个表中:

 function myfunction(target){ if($(target).closest("tr").find(".input-city").length){ console.log('true'); }else{ console.log('false'); } }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <h1>Working</h1> <table> <tr> <td><input type="text" class="form-control input-state" onclick="myfunction(this)"></td> <td><input type="text" class="form-control input-city" onclick="myfunction(this)"></td> </tr> </table> <h1>Not Working</h1> <tr> <td><input type="text" class="form-control input-state" onclick="myfunction(this)"></td> <td><input type="text" class="form-control input-city" onclick="myfunction(this)"></td> </tr>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM