jQuery动态添加元素

jQuery动态添加元素,jquery,Jquery,我添加了一个div的点击功能,发现这段代码运行良好 function GetHtml() { var len = $('.extraPerson').length; var $html = $('.extraPersonTemplate').clone(); $html.find('[id=condition]')[0].name="condition[]"; // drop-down $html.find('[id=data_type]')[0].name="

我添加了一个div的点击功能,发现这段代码运行良好

function GetHtml()
{
    var len = $('.extraPerson').length;
    var $html = $('.extraPersonTemplate').clone();

    $html.find('[id=condition]')[0].name="condition[]"; // drop-down
    $html.find('[id=data_type]')[0].name="data_type[]";
    $html.find('[id=filter]')[0].name="filter[]";
    $html.find('[id=detail]')[0].name="detail[]";

    return $html.html();    
}
现在,我想添加更多元素,但需要检查

IF <new_element> NO EXIST THEN 
$html.find('[id=new_element]')[0].name="new_element[]";
如果不存在,则
$html.find('[id=new_element]')[0].name=“new_element[]”;
但不确定如何使用

if( $html.find('[id=new_element]').length == 0 ) {
  // add your element here
}
如果没有更多关于你的结构看起来像什么或者你想添加什么的上下文,我就帮不上什么忙了

此外,您的发现可以简化为:

$("#condition", $html).attr("name", "condition[]"); // drop-down
$("#data_type", $html).attr("name", "data_type[]");
$("#filter", $html).attr("name", "filter[]");
$("#detail", $html).attr("name", "detail[]");

请尝试使用下面的代码段

if($html.find('[id=new_element]').Length == 0)
{
    $html.find('[id=new_element]')[0].name="new_element[]";
}

请尝试下面的代码:

if(typeof $("identificate_your_element").get(0) == "undefined"){
    // do stuff
}

首先看看你的函数在做什么,然后说你想要什么

    function GetHtml()
    {
        // Getting length of element with class extraPerson
        var len = $('.extraPerson').length;

        // Making clone of html element having class extraPersonTemplate
        var $html = $('.extraPersonTemplate').clone();

        // Finding html element having ID[condition] inside cloned element and setting name atrribute condition[]
        $html.find('[id=condition]')[0].name="condition[]"; // drop-down
        // Finding html element having ID[extraPersonTemplate] inside cloned element and setting name atrribute data_type[]
        $html.find('[id=data_type]')[0].name="data_type[]";
        // Finding html element having ID[filter] inside cloned element and setting name atrribute filter[]
        $html.find('[id=filter]')[0].name="filter[]";
        // Finding html element having ID[detail] inside cloned element and setting name atrribute detail[]
        $html.find('[id=detail]')[0].name="detail[]";


        //finally returning clone element with setting all the element attribute present inside it
        return $html.html();    
    }
在这里,您将克隆一个html元素,并设置该元素中已经存在的元素的name属性

如果必须添加新元素,请尝试以下操作

IF <new_element> NO EXIST THEN 
    $html.append($('<div>NEW DIV</div>'));
如果不存在,则
$html.append($('newdiv'));