JS将DOM作为函数

时间:2017-04-26 22:42:22

标签: javascript dom

我有这段代码:

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

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

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

“this”是按钮的DOM。

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

谢谢!

2 个答案:

答案 0 :(得分: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 :(得分:1)

我不确定这是否正是您想要的,但只要按钮添加到DOM,您就可以使用MutationObserver来调用“create”:

  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。

相关问题