2017-04-26 82 views
0

的参数我有这样的代码:JS通过DOM的功能

let button = document.createElement('button'); 
button.addEventListener('click', create, false); 

当我点击按钮的功能“创建”被执行。我的功能“创建”是:

function create(event) { 
event.preventDefault(); 
console.log(this); 
} 

“this”是按钮的DOM。

现在,我想要的是,创建按钮后,“创建”功能自动执行,但传递按钮的DOM作为参数。 也就是说,不需要交互来执行该功能。但“创建”功能的结果必须相同。

谢谢!

+0

你的答案是? – Subgeo

+0

上面的代码返回:

+0

所以你想在创建按钮后执行该功能,而不点击它? – Subgeo

回答

1

我没有你想达到什么样的想法,但这里是代码...

随着事件侦听器:

var button = document.createElement('button'); 
 
button.innerHTML = 'OK'; 
 
document.body.appendChild(button); 
 

 
button.addEventListener('click', create, false); 
 

 
function create(event) { 
 
    event.preventDefault(); 
 
    console.log(this); 
 
}

没有事件收听者:

var button = document.createElement('button'); 
 
button.innerHTML = 'OK'; 
 
document.body.appendChild(button); 
 

 
create.bind(button)(); 
 

 
function create() { 
 
    console.log(this); 
 
}

1

我不知道这是否是你想要什么,但你可以使用一个MutationObserver叫“创造”每当一个按钮被添加到DOM:

function create(event) { 
 
    // Runs whenever a button is added to the DOM; this is the button element 
 
    console.log(this); 
 
    } 
 

 
    // Observe additions of new DOM nodes to the body and its children 
 
    var observer = new MutationObserver(function(mutations) { 
 
    mutations.forEach(function(mutation) {   
 
     mutation.addedNodes.forEach(function(node) { 
 
     if (node.tagName == 'BUTTON') { 
 
      // Call create with the added button as 'this' 
 
      create.call(node); 
 
     } 
 
     }); 
 
    }); 
 
    }); 
 

 
    // Setup the observer--look only for node additions and removals in body and all child elements 
 
    observer.observe(document.body, {childList: true, attributes: false, characterData: false, subtree: true}); 
 

 
    var button = document.createElement('button'); 
 
    document.body.appendChild(button);

请注意,当按钮被添加到DOM,而不是按钮被创建时,调用发生。因此,如果您调用document.createElement('button')但不将其附加到DOM,则不会调用create。