jQuery在脚本中创建类

jQuery created class inside script

本文关键字:创建 脚本 jQuery      更新时间:2023-09-26

我想点击一个段落并显示一些东西,它有一个类在脚本标签内创建,但我不能使它可点击。有人能告诉我怎么做吗?

下面是我的部分代码。

$('#three-star').click(function(){
    var id=$('#elements-container').children().length+1;
    $('#elements-container').append('<p id="'+id+'" class = "edit">Type your question here</p>');
});
$('p.edit').click(function(){               
    $('#editor').show();
});

当我点击"在这里输入你的问题"时,我该如何做show() ?

使用事件委托

$('#elements-container').on("click" , 'p.edit',function(){               
            $('#editor').show();
        });

event listener可以委托给父元素。

$('#container').on('click', '.edit', function(event) {
    // do something
});

当有人单击编辑链接时,事件会在DOM中冒泡,并被侦听器捕获。

这里有关于事件冒泡的更多信息

工作小提琴小提琴

使用以下

 $("p.edit").on("click",function(){               
     $('#editor').show();
 });

因为$('p.edit').click(function(){这不支持新的动态创建的内容。所以使用on事件

在这里工作动态创建段落,并为元素添加事件。

var comment = "Type your question here.";
var newParagraph = document.createElement('p');
newParagraph.textContent = comment;
newParagraph.id = 3;
newParagraph.onclick = function () {
    $('#qs_div').show();
};