Home > Web Front-end > JS Tutorial > An example discussion on jQuery's problem of determining whether an element exists_jquery

An example discussion on jQuery's problem of determining whether an element exists_jquery

WBOY
Release: 2016-05-16 16:41:25
Original
1298 people have browsed it

That’s right, when I was doing jQuery training recently, I encountered a problem when jQuery determines whether an element exists.

The question is as follows: Please add Id=rad4 after "Select Button 3". In the selected state, the HTML control with the text "Select Button 4" can only be added once (you can choose to use js native or JQuery to implement it)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

function addradio()

{

if (!document.getElementById("rad4"))

{

var main = document.getElementById("radioContainer");

 

var input = document.createElement("input");

input.setAttribute("type", "radio");

input.setAttribute("id", "rad4");

var span = document.createElement("span");

var txt = document.createTextNode("选择按钮4");

span.appendChild(txt);

main.appendChild(input);

main.appendChild(span);

}

}

Copy after login

It is enough to determine whether the object exists. if (!document.getElementById("rad4")) but in jQuery if (!$("#rad4")) is always false. I thought it was the same as javascript but it is not the case

In jQuery. Once wrapped by the $("") wrapper, it is an object, not null or undefined, so!$("#rad4")

Always false. The correct approach is as follows

If there is no object in the wrapper, the length will be 0; that’s all you need

1

2

3

4

5

6

7

8

9

10

11

12

13

14

$(function ()

{

 

$(".domtree div:eq(6) input:eq(1)").click(function ()

{

if ($("#rad4").length < 1)

{

$("<input type='radio' id='rad4'> <span>选择按钮4</span>").appendTo($("#radioContainer"));

}

}

)

 

}

)

Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template