About jQuery append() and how to check if an element has been appended

前端 未结 6 990
天命终不由人
天命终不由人 2021-01-11 10:21

I made a very simple button click event handler, I would like to have

element be appended when button clicked, you can check my code

相关标签:
6条回答
  • 2021-01-11 11:03

    http://jsfiddle.net/j36ye/17/

    $("#search_btn").click(function(){
        if(($('#other').length) == 0) {
            $("#wrapper").append("<p id='other'>I am here</p>");
        }
        return false
    });
    

    Or

    var other_appended = false;
    
    $("#search_btn").click(function(){
        if(other_appended == false) {
             $("#wrapper").append("<p id='other'>I am here</p>");
              other_appended = true;
        }
        return false;
    });
    
    0 讨论(0)
  • 2021-01-11 11:06

    1) jsFiddle loads in MooTools by default, you need to include jQuery for this to work. There is not a reason in the world why that example wouldn't work. (Assuming that the $ is actually mapped to the jQuery object, that is.)

    2) You can check the nextSibling of a DOMElement, or use the next() jQuery method, like so:

    if(!$('#something').next().length) {
       //no next sibling.
    }
    
    0 讨论(0)
  • 2021-01-11 11:08
    1. You are using mootools and not jQuery.

    2. To check if your element exists

    if($('#other').length > 0)

    So if you do not want to append the element twice:

    $("#search_btn").click(function() {
        if($('#other').length == 0) {
            $("#wrapper").append("<p id='other'>I am here</p>");
        }
    });
    

    Or, you can use the .one(function)[doc]:

    $("#search_btn").one('click', function() {
        $("#wrapper").append("<p id='other'>I am here</p>");
    });
    
    0 讨论(0)
  • 2021-01-11 11:23

    How to check if an element exists:

    if($("p#other").length > 0) {
        // a p element with id "other" exists
    }
    else {
        // a p element with id "other" does not exist
    }
    
    0 讨论(0)
  • 2021-01-11 11:23

    Your fiddle is using the moo tools framework. Change it to use the jquery framework on the left and it works. See http://jsfiddle.net/KxGsj/

    0 讨论(0)
  • 2021-01-11 11:24

    check if element is already appended:

    alert($(this).parent().length?'appended':'not appended');
    
    0 讨论(0)
提交回复
热议问题