附加到带有重复类的div [英] Append to a div with a recurring class
问题描述
我有一个JS,只需点击一个按钮,将以下内容附加到Web表单。当单击div .remove
时,将删除最接近的 new-attribute
div。它工作正常。
I have a piece of JS that appends the following to a web form on the click of a button. When the div .remove
is clicked the closest new-attribute
div is removed. It works fine.
<div class="new-attribute">
<h3>New Attribute</h3>
<label for="attributeName3">Name:</label>
<input class"attribute"="" type="text" name="attributeName3">
<label for="attributeType3">Type:</label>
<select id="t" class="attribute" name="attributeType3">
<option value="text" selected="">Text</option>
<option value="checkbox">Checkbox</option>
<option value="select-list">Select Option List</option>
<option value="notes">Notes</option>
</select>
<div class="option"></div>
<div class="remove">Delete</div>
</div>
在div选项我有代码添加另一个表单字段选择列表。这是行不通的。我不知道为什么。没有变量名冲突。我不应该给选择一个id,因为它是经常性的,我只是想让它工作之前,我使它符合。
In the div "option" I have code to add another form field on the selection of "select-list" in the select input. It does not work. I do not know why. No variable names are clashing. I'm away I shouldnt give the select an id because it is recurrent, I just want to get it working before I make it compliant.
有麻烦:
//select temp
var select="<div class=\"new-option\">"
+ "<h3>new option</h3>"
+ "<label for=\"attributeName"+count+"\">New otion:</label>"
+ "<input class\"attribute\" type=\"text\" name=\"attributeName"+count+"\">"
+ "</div>";
//get value of select
$('#t').change(function() {
var selectVal = $('#t :selected').val();
if (selectVal == "select-list") {
$(this).closest('.option').append(select);
}
});
此代码适用于 $(select).appendTo('。option' );
然而,它将代码附加到页面上的option类的每个实例。
The code works with $(select).appendTo('.option');
However it appends the code to every instance of the "option" class on the page. I only want it to append to the current or closest one.
提前感谢您
推荐答案
问题是因为 closest()
查找与选择器匹配的最近父元素的DOM,而 .option
是 #t
的同级。尝试改用 next()
:
The problem is because closest()
looks up the DOM for the nearest parent element matching the selector, but .option
is a sibling of #t
. Try using next()
instead:
$('#t').change(function() {
if ($(this).val() == "select-list") {
$(this).next('.option').append(select);
}
});
这篇关于附加到带有重复类的div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!