jQuery .click()和.on('点击')无效

时间:2015-03-29 13:19:35

标签: jquery

我对JavaScript很新,我一直在尝试编辑此code on this page以便为我工作。到目前为止,我已成功设法在每个表单的顶部获取正确的表单编号,但在删除表单字段集后,我无法获取表单编号。这是迄今为止的代码: HTML:     

<input type="button" value="Remove review" class="delete" /><br /><br />
<p class='sometext'>Some text </p>

<input name="cd" value="title" />

<select name="rankingsel">
    <option>Rating</option>
    <option value="excellent">Excellent</option>
    <option value="good">Good</option>
    <option value="ok">OK</option>
    <option value="poor">Poor</option>
    <option value="bad">Bad</option>
</select><br /><br />

<textarea rows="5" cols="20" name="review">Short review</textarea>
<br />Radio buttons included to test them in Explorer:<br />
<input type="radio" name="something" value="test1" />Test 1<br />
<input type="radio" name="something" value="test2" />Test 2

              

JavaScript的:

var counter = 0;

function moreFields() {
    counter+=1;
    var newFields = document.getElementById('readroot').cloneNode(true);
    newFields.id = '';
    newFields.style.display = 'block';
    var newField = newFields.childNodes;
    var n = $("[class^='sometext'").length;
    for (var i=0;i<newField.length;i+=1) {
        var theName = newField[i].name
        if (theName){
            newField[i].name = theName + counter;
        }
        if (newField[i].className == 'sometext'){
            $(newField[i]).append(document.createTextNode(n));
        }
    }
    var insertHere = document.getElementById('writeroot');
    insertHere.parentNode.insertBefore(newFields,insertHere);
}

window.onload = moreFields;
$(document).ready(function(){
    $('#moreFields').click(function(){
        moreFields();
    });
    $('#readroot').on('click','.delete',function(){
        this.parentNode.parentNode.removeChild(this.parentNode);
        var countClass = 0;
        $('.sometext').each(function(){
            countClass += 1;
            this.innerHTML = "Some text " + countClass;
        });
    });
});

当我点击删除评论按钮并且我也尝试执行$('。delete')时,问题是没有任何反应。请点击,但这也不起作用。以下是JSFiddle上的代码。

1 个答案:

答案 0 :(得分:0)

您呼叫.on()的元素必须在呼叫时存在。在您的情况下,在调用#readroot时,动态添加的.on()克隆不存在。对绑定时存在的内容调用.on(),例如document

演示:https://jsfiddle.net/dfht2ky8/2/

代码:

$(document).on('click', '.delete', function() {
    ...
});