JQuery Clone()问题。克隆代码块的简单程序出乎意料地表现出来

时间:2012-10-14 21:04:57

标签: javascript jquery html css

我是这个领域的初学者。 我创建了一个HTML页面,点击一些“+”/“ - ”按钮,我分别从Multiple.js文件调用add()和remove()来添加或删除HTML页面中的代码块。但我得到了意想不到的结果。文件如下: 多个Group Selection.html

<!DOCTYPE HTML >
<HTML>
<HEAD>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<link rel="stylesheet" href="style.css">
<TITLE>Multiple Group Selections</TITLE>
<script src="Multiple.js" type="text/javascript"></script>
</HEAD>
<BODY BGCOLOR="#FDF5E6">
<H2 ALIGN="CENTER">Multiple Group Selections</H2>
<div id="clonedInput1" class="clonedInput">
<FIELDSET class="field">
<LEGEND ALIGN="RIGHT">
<button type="button" class = "clone" onclick={add();}  >+</button>
<button type="button" class = "remove" onclick={remove();}>-</button>
</LEGEND>
Field 2A: <INPUT TYPE="TEXT" NAME="field2A" VALUE="Field A"><BR>
Field 2B: <INPUT TYPE="TEXT" NAME="field2B" VALUE="Field B"><BR>
Field 2C: <INPUT TYPE="TEXT" NAME="field2C" VALUE="Field C"><BR>
</FIELDSET>
</div>
</BODY>
</HTML>

Multiple.js:

function add(){
var regex = /^(.*)(\d)+$/i;
var cloneIndex = $(".clonedInput").length;

$("button.clone").live("click", function(){
$(this).parents(".clonedInput").clone()
    .appendTo("body")
    .attr("id", "clonedInput" +  cloneIndex)
    .find("*").each(function() {
        var id = this.id || "";
        var match = id.match(regex) || [];
        if (match.length == 3) {
            this.id = match[1] + (cloneIndex);
        }
});
cloneIndex++;
});

}
function remove(){
 $("button.remove").live("click", function(){
 $(this).parents(".clonedInput").remove();
});
}

的style.css

 .clone {
 font-family: Verdana, Arial, Helvetica, sans-serif; 
 font-size: 12px;  
 font-weight: bold; 
 color: #00ffff;
 Background-COLOR: white;
 border: black;
 border-style: solid;
 border-width: 1px;
 }
.remove{
font-family: Verdana, Arial, Helvetica, sans-serif; 
font-size: 12px; 
font-weight: bold; 
color: #00ffff;
Background-COLOR: white;
border: black;
border-style: solid;
border-width: 1px;
}

我想要的只是点击“+”按钮必须附加到。单击“ - ”按钮也应该将其删除。请帮帮我。我很累。

2 个答案:

答案 0 :(得分:3)

您肯定误入歧途的一个地方是尝试将内联onclick处理程序与不显眼的jquery点击处理程序混合使用。特别是当它们都是相同元素的点击处理程序时。如果你刚刚开始使用jQuery,那么最好的方法就是不要使用任何内联的javascript。

阅读你的add()函数,你必须点击添加按钮,然后创建一个jQuery clcik处理程序......但是点击已经发生,所以处理程序不会在第一次触发。

删除内联onclick并展开add()remove()函数会将所有javascript从标记中取出并使其更容易理解。

DEMO:http://jsfiddle.net/Xfg7P/

注意:fieldset应该在form form标签内,标记中没有form标签。

答案 1 :(得分:0)

我简化了克隆元素的功能,并添加了新的动态id

$('#btnclone').on('click', function() {
    var lastid = $('[id^="clonedInput"]').length + 1;
    $(".clonedInput")
        .last()
        .clone()
        .attr('id', 'clonedInput' + lastid)
        .appendTo("body")
    $('input').each(function() {
        $(this).val('PARENT DIV ID =  ' + $(this).parent().attr('id'))
    })
})

在此测试:http://jsfiddle.net/RASG/MjMh5/