Home > Article > Web Front-end > An example discussion on jQuery’s problem of determining whether an element exists_jquery
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)
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); } }
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
$(function () { $(".domtree div:eq(6) input:eq(1)").click(function () { if ($("#rad4").length < 1) { $("<input type='radio' id='rad4'> <span>选择按钮4</span>").appendTo($("#radioContainer")); } } ) } )