这个问题在这里已有答案:
嗨,我正在尝试创建一个部分显示的列表,如果您单击阅读更多,您将能够看到所有列表。我找到了这个插件:https://github.com/solarmosaic/jquery-show-first
但是,当我尝试在javascript中新插入的HTML上使用它时,它不起作用。如果HTML在开头的HTML文件中,它就可以工作。
这是我的代码的一部分:
var associatedEntities = associated[a].split("|");
var personDone = false;
var placeDone = false;
var keywordDone = false;
var itemDone = false;
for (var d = 0; d<associatedEntities.length; d++){
if(associatedEntities[d].includes("@")){
var contents = associatedEntities[d].split('@');
if(associatedEntities[d].includes('person/')){
if(personDone == false){
associatedWithHTML+="<ul class = \"show-first\" data-show-first-count=\"3\">";
personDone = true;
}
associatedWithHTML+="<li><a target=\"_blank\" href=\"PersonResult.html?id="+contents[0].trim()+"\" >"+contents[1]+"</a><br></li>";
}else if (associatedEntities[d].includes('place/')){
if(placeDone == false){
associatedWithHTML+="<ul class = \"show-first\" data-show-first-count=\"3\">";
placeDone = true;
}
associatedWithHTML+="<li><a target=\"_blank\" href=\"PlaceResult.html?id="+contents[0].trim()+"-"+contents[1]+"\" >"+contents[1]+"</a><br></li>";
}else if (associatedEntities[d].includes('item/')){
if(itemDone == false){
associatedWithHTML+="<ul class = \"show-first\" data-show-first-count=\"3\">";
itemDone = true;
}
associatedWithHTML+="<li><a target=\"_blank\" href=\"ItemResult.html?id="+contents[0].trim()+"\" >"+contents[1]+"</a><br></li>";
}
}else{
if(keywordDone == false){
associatedWithHTML+="<ul class = \"show-first\" data-show-first-count=\"3\">";
keywordDone = true;
}
associatedWithHTML+="<li><span>"+associatedEntities[d]+"</span><br></li>";
}
}
}
associatedWithHTML+="</ul><hr></div>";
document.getElementById("DeedDate").innerHTML+=newHTML+associatedWithHTML+"</div>";
在页面加载后插入的HTML将不会应用任何javascript事件/侦听器,这些事件/侦听器通常应用于页面加载时具有匹配的id / selectors的元素(除非您使用mutator事件)。
您必须以某种方式设置事件侦听器,以便在插入DOM节点时“动态”添加事件。
//Jquery: Instead of this for attaching an event
$(".my-element").click(function() {
//Some code here...
});
//Jquery: You will need to do this to catch all elements
$(document).on("DOMNodeInserted", ".my-element", function() {
$(this).click(function() {
//Some code here...
});
});
//Vanilla javascript
document.addEventListener("DOMNodeInserted", function (e)
{
if(e.target.classList.contains("my-element")) {
e.target.addEventListener("click", function() {
//Some code here...
});
}
}, false);
现在,你是从插件的上下文中提出这个问题,但这就是正在发生的事情。该插件不会将其事件应用于节点插入时的事件,而是在页面加载时。您可以修改提供的代码来执行此操作,或者添加一些在节点插入DOM中注册所需事件的内容。
注意:只选择使用DOMNodeInserted的上述两个示例解决方案中的一个。这取代了该元素的正常“单击”事件注册。除了添加为同一选择器注册的DOMNodeInsert事件之外,不要注册click事件。