简体   繁体   English

检查jQuery中是否存在元素

[英]check for element presence in jquery

I have a page in which i have to search for presence of element depending on first input in the first form only 我有一个页面,我只能根据第一种形式的第一种输入来搜索元素的存在

<input type="text" /><!-- first input -->
<button></button>
<div>
    <form><input value="3" /></form> <!-- first form -->
    <form><input value="3" /></form>
</div>

and script 和脚本

$("button").click(function()
{
    if( $(this).next().children("form").first().has("input[value='" + $(this).prev().val() + "']") )
        alert("Present");
    else
        alert("Absent");
});

But it's not working 但这没用

You can check the presence of an element by checking the length of the collection a query returns: 您可以通过检查查询返回的集合的长度来检查元素的存在:

For example, if i were to check if i had forms: 例如,如果我要检查是否有表格:

var forms = $('form').length //0 if none, at least 1 if any

The problem is that the .has() method doesn't return a boolean, it returns a jQuery object, specifically it "constructs a new jQuery object from a subset of the matching elements". 问题在于.has()方法不返回布尔值,而是返回jQuery对象,特别是它“从匹配元素的子集构造新的jQuery对象”。 You need to check the length of that object to see if any elements matched: 您需要检查该对象的长度,以查看是否有任何匹配的元素:

if($(this).next().children("form").first()
           .has("input[value='"+$(this).prev().val()+"']").length != 0)

Demo: http://jsfiddle.net/mmQHB/ 演示: http//jsfiddle.net/mmQHB/

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

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