是否有任何方法可以监听附加在文档上的文档片段?

问题描述 投票:0回答:1

我有一个程序,可以将一些标记放入文档片段中,然后可以将其附加到文档上。我想在附加代码后执行一些代码,就像connectedCallback在自定义元素上的工作方式一样。这可能吗?

将文档片段附加到文档会清空它,这意味着我可能可以使用突变观察器,但是如果有人在附加它之前对其进行了修改,那么该代码将执行,这不是我想要的行为。

javascript html dom
1个回答
0
投票

阅读我的评论,然后查看以下内容:

//<![CDATA[
/* js/external.js */
var doc, bod, frag, shuffle, M, I; // for use on other loads
addEventListener('load', function(){
doc = document; bod = doc.body; frag = doc.createDocumentFragment();
shuffle = function(array){
  var a = array.slice();
  a.sort(function(b, c){
    return 0.5 - Math.random();
  });
  return a;
}
M = function(tag){
  return doc.createElement(tag);
}
I = function(id){
  return doc.getElementById(id);
}
/* you could put the below on aother page if you like (except for the load end) */
function createList(list, doneFunc){
  var li;
  list.forEach(function(v){
    li = M('li'); li.textContent = v; frag.appendChild(li);
  });
  if(doneFunc)doneFunc(frag);
  return frag;
}

var ul = I('simple_list'), list = ['This', 'list', 'is', 'very', 'simple'], n = 0;
ul.appendChild(createList(list));
I('test').onclick = function(){
  ul.innerHTML = '';
  ul.appendChild(createList(shuffle(list), function(frag){
   // this is the doneFunc - you don't have to use an Anonymous function
   console.log('Test number '+(++n)+'. Careful, frag is entire fragment!');
 }));
}
}); // load end
//]]>

  
<ul id='simple_list'></ul>
<input id='test' type='button' value='dynamic test' />

console.log是动态执行的,因为它在doneFunc中。

© www.soinside.com 2019 - 2024. All rights reserved.