簡體   English   中英

附加到具有重復班級的div

[英]Append to a div with a recurring class

我有一塊JS,單擊一下按鈕即可將以下內容附加到Web表單中。 單擊div .remove時,將刪除最接近的new-attribute div。 工作正常。

<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“選項”中,我有代碼在選擇輸入中的“選擇列表”選擇上添加另一個表單字段。 這是行不通的。 我不知道為什么。 沒有變量名沖突。 我不在,我不應該給select一個ID,因為它是重復出現的,我只想在使其符合標准之前就可以使其正常工作。

這是我遇到麻煩的Js:

//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”類的每個實例。 我只希望它附加到當前或最接近的那個。

先感謝您

問題在於,因為.option closest()在DOM中查找與選擇器匹配的最近父元素,但是.option#t的同級對象。 嘗試改用next()

$('#t').change(function() {
    if ($(this).val() == "select-list") {
        $(this).next('.option').append(select);
    }   
});

嘗試這個

http://jsfiddle.net/7WC4G/1/

$('#bob').change(function(){
    $('#nuform').append('<p>your new form here</p>');
});

避免使用next,prev,因為如果更改順序,它可能會失敗。 而是嘗試使用兄弟姐妹而不是代碼中最接近的兄弟姐妹:

$(this).siblings('.option').append(select);

在此處閱讀有關此內容的更多信息: http : //api.jquery.com/siblings/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM