为什么使用setAttribute设置的onclick属性无法在IE中工作?

Aeo*_*eon 46 javascript internet-explorer

今天遇到这个问题,发布以防其他人有同样的问题.

var execBtn = document.createElement('input');
execBtn.setAttribute("type", "button");
execBtn.setAttribute("id", "execBtn");
execBtn.setAttribute("value", "Execute");
execBtn.setAttribute("onclick", "runCommand();");
Run Code Online (Sandbox Code Playgroud)

结果是让IE在动态生成的元素上运行onclick,我们不能使用setAttribute.相反,我们需要使用包含我们想要运行的代码的匿名函数在对象上设置onclick属性.

execBtn.onclick = function() { runCommand() };
Run Code Online (Sandbox Code Playgroud)

不好的想法:

你可以做

execBtn.setAttribute("onclick", function() { runCommand() });
Run Code Online (Sandbox Code Playgroud)

但根据@scunliffe,它将在非标准模式下在IE中中断.

你完全不能这样做

execBtn.setAttribute("onclick", runCommand() ); 
Run Code Online (Sandbox Code Playgroud)

因为它立即执行,并将runCommand()的结果设置为onClick属性值,也不能这样做

execBtn.setAttribute("onclick", runCommand);
Run Code Online (Sandbox Code Playgroud)

Sha*_*atz 41

要使这个工作在FF和IE中你必须写两种方式:


    button_element.setAttribute('onclick','doSomething();'); // for FF
    button_element.onclick = function() {doSomething();}; // for IE
Run Code Online (Sandbox Code Playgroud)

感谢这篇文章.

UPDATE:这是证明有时必须使用的setAttribute!如果您需要从HTML中获取原始onclick属性并将其添加到onclick事件,则此方法有效,因此不会覆盖它:

// get old onclick attribute
var onclick = button_element.getAttribute("onclick");  

// if onclick is not a function, it's not IE7, so use setAttribute
if(typeof(onclick) != "function") { 
    button_element.setAttribute('onclick','doSomething();' + onclick); // for FF,IE8,Chrome

// if onclick is a function, use the IE7 method and call onclick() in the anonymous function
} else {
    button_element.onclick = function() { 
        doSomething();
        onclick();
    }; // for IE7
}
Run Code Online (Sandbox Code Playgroud)

  • 但是`getAttribute` /`setAttribute`的优点是什么呢?使用`.onclick`属性而不是get和set都可以在所有浏览器中使用,并且不会引入麻烦的范围差异. (4认同)
  • button_element.onclick = function()..适用于IE和Firefox.就此而言,它也适用于Opera,Safari和Chrome.是否需要setAttribute(对于Firefox)? (3认同)
  • `onclick`方式在FF和IE中运行良好.没有理由使用`setAttribute`版本. (3认同)
  • 这仍然相关吗? (2认同)

scu*_*ffe 10

有一个的属性的集合,你不能在IE中设置使用().setAttribute其中包括每一个内联事件处理程序.

详情请见此处:

http://webbugtrack.blogspot.com/2007/08/bug-242-setattribute-doesnt-always-work.html


小智 7

效果很好!

现在使用两种方式似乎都是不必要的:

execBtn.onclick = function() { runCommand() };
Run Code Online (Sandbox Code Playgroud)

显然适用于所有当前的浏览器.

在Windows上的当前Firefox,IE,Safari,Opera,Chrome中进行了测试; Ubuntu上的Firefox和Epiphany; 没有在Mac或移动系统上测试过.

  • 克雷格:我试试"document.getElementById(ID).type ='password';
  • 有没有人用不同的引擎检查"AddEventListener"方法?


Aco*_*orn 6

对于跨浏览器兼容的事件绑定来说,这是一个令人惊奇的功能。

从http://js.isite.net.au/snippets/addevent获取

有了它,您就可以安心Events.addEvent(element, event, function);无忧!

例如:(http://jsfiddle.net/Zxeka/

function hello() {
    alert('Hello');
}

var button = document.createElement('input');
button.value = "Hello";
button.type = "button";

Events.addEvent(input_0, "click", hello);

document.body.appendChild(button);
Run Code Online (Sandbox Code Playgroud)

这是函数:

// We create a function which is called immediately,
// returning the actual function object.  This allows us to
// work in a separate scope and only return the functions
// we require.
var Events = (function() {

  // For DOM2-compliant browsers.
  function addEventW3C(el, ev, f) {
    // Since IE only supports bubbling, for
    // compatibility we can't use capturing here.
    return el.addEventListener(ev, f, false);
  }

  function removeEventW3C(el, ev, f) {
    el.removeEventListener(ev, f, false);
  }

  // The function as required by IE.
  function addEventIE(el, ev, f) {
    // This is to work around a bug in IE whereby the
    // current element doesn't get passed as context.
    // We pass it via closure instead and set it as the
    // context using call().
    // This needs to be stored for removeEvent().
    // We also store the original wrapped function as a
    // property, _w.
    ((el._evts = el._evts || [])[el._evts.length]
        = function(e) { return f.call(el, e); })._w = f;

    // We prepend "on" to the event name.
    return el.attachEvent("on" + ev,
        el._evts[el._evts.length - 1]);
  }

  function removeEventIE(el, ev, f) {
    for (var evts = el._evts || [], i = evts.length; i--; )
      if (evts[i]._w === f)
        el.detachEvent("on" + ev, evts.splice(i, 1)[0]);
  }

  // A handler to call all events we've registered
  // on an element for legacy browsers.
  function addEventLegacyHandler(e) {
    var evts = this._evts[e.type];
    for (var i = 0; i < evts.length; ++i)
      if (!evts[i].call(this, e || event))
        return false;
  }

  // For older browsers.  We basically reimplement
  // attachEvent().
  function addEventLegacy(el, ev, f) {
    if (!el._evts)
      el._evts = {};

    if (!el._evts[ev])
      el._evts[ev] = [];

    el._evts[ev].push(f);

    return true;
  }

  function removeEventLegacy(el, ev, f) {
    // Loop through the handlers for this event type
    // and remove them if they match f.
    for (var evts = el._evts[ev] || [], i = evts.length; i--; )
      if (evts[i] === f)
        evts.splice(i, 1);
  }

  // Select the appropriate functions based on what's
  // available on the window object and return them.
  return window.addEventListener
      ? {addEvent: addEventW3C, removeEvent: removeEventW3C}
      : window.attachEvent
          ? {addEvent: addEventIE, removeEvent: removeEventIE}
          : {addEvent: addEventLegacy, removeEvent: removeEventLegacy};
})();
Run Code Online (Sandbox Code Playgroud)

如果你不想使用这么大的功能,这应该适用于几乎所有浏览器,包括 IE:

if (el.addEventListener) { 
    el.addEventListener('click', function, false); 
} else if (el.attachEvent) { 
    el.attachEvent('onclick', function); 
} 
Run Code Online (Sandbox Code Playgroud)

回答克雷格的问题。您将必须创建一个新元素并复制旧元素的属性。这个函数应该可以完成这项工作:(来源

function changeInputType(oldObject, oType) {
  var newObject = document.createElement('input');
  newObject.type = oType;
  if(oldObject.size) newObject.size = oldObject.size;
  if(oldObject.value) newObject.value = oldObject.value;
  if(oldObject.name) newObject.name = oldObject.name;
  if(oldObject.id) newObject.id = oldObject.id;
  if(oldObject.className) newObject.className = oldObject.className;
  oldObject.parentNode.replaceChild(newObject,oldObject);
  return newObject;
}
Run Code Online (Sandbox Code Playgroud)


cdm*_*kay 5

或者你可以使用 jQuery 并避免所有这些问题:

var execBtn = $("<input>", {
       type: "button",
       id: "execBtn",
       value: "Execute"
    })
    .click(runCommand);        
Run Code Online (Sandbox Code Playgroud)

jQuery 还将解决所有跨浏览器问题。