简体   繁体   English

如何在jQuery中搜索附加的HTML?

[英]how to search appended html in jquery?

I want create somthing like wordpress comment reply form. 我想创建诸如wordpress评论回复表格之类的东西。 in WP when you click on reply button a from apear under the reply button. 在WP中,当您单击回复按钮下方的ap上的回复按钮a时。 I do appending form after clicking reply button, but my problem is if i click again another form append to container. 我在单击“回复”按钮后确实添加了表单,但是我的问题是如果我再次单击另一种添加到容器的表单。 for handeling this I want search container before append form, if form exist it sholudn't append another one but it seems search wouldn't work for appended html. 为了处理这个问题,我想在附加表单之前搜索容器,如果表单存在,它就不会附加另一个表单,但是似乎对附加的html来说搜索是行不通的。 what's your suggestion for this problem? 您对这个问题有什么建议?

$(document).on('click','.reply-btn',function(){
 ...

            var form="<div class='col-xs-12' >"+
                  "<form role='form' method='post'>"+
                    ....
                  "</form>"+
             "</div>";

            var container=$(this).closest('div');

            if(container.html().search(form)<0){
                container.append(form)
            }else{
                alert('it'e also appended') 
            }

        })// .reply-btn
 $(document).on('click','.reply-btn',function(){
            var form="<div class='col-xs-12' >"+
                  "<form role='form' method='post'>"+
                    ....
                  "</form>"+
             "</div>";

            var container=$(this).closest('div');


            if(container.find('form').length <1)
                container.append(form)
            }else{
                alert('it is also appended') 
            }

        });

Your html string and the html returned by the dom structure may not be the same, what you should do is to check whether container has a form like 您的html字符串和dom结构返回的html可能不相同,您应该做的是检查容器是否具有如下形式:

$(document).on('click', '.reply-btn', function () {


    var container = $(this).closest('div');

    if (container.find('form').length == 0) {
        var form = "<div class='col-xs-12' >" +
            "<form role='form' method='post'>" + ....
            "</form>" +
            "</div>";
        container.append(form)
    } else {
        alert('it\' e also appended ')
    }

})

use find and length to check the element present or not 使用查找和长度检查元素是否存在

   if(container.find("form").length){
     // already there
}

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

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