50

今日この問題に遭遇し、他の誰かが同じ問題を抱えている場合に備えて投稿しました。

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

IEに動的に生成された要素に対してonclickを実行させることが判明したため、setAttributeを使用できません。代わりに、実行するコードをラップする無名関数を使用して、オブジェクトにonclickプロパティを設定する必要があります。

execBtn.onclick = function() { runCommand() };

悪いアイデア:

できるよ

execBtn.setAttribute("onclick", function() { runCommand() });

ただし、@ scunliffeによると、非標準モードのIEでは機能しなくなります。

あなたはこれをまったく行うことができません

execBtn.setAttribute("onclick", runCommand() ); 

すぐに実行され、runCommand()の結果がonClick属性値に設定されるためです。

execBtn.setAttribute("onclick", runCommand);
4

13 に答える 13

11

よく働く!

現在、両方の方法を使用する必要はないようです。

execBtn.onclick = function() { runCommand() };

現在のすべてのブラウザで動作するようです。

Windows 上の現在の Firefox、IE、Safari、Opera、Chrome でテスト済み。Ubuntu の Firefox と Epiphany。Mac またはモバイル システムではテストされていません。

  • Craig: "document.getElementById(ID).type='password'; を試してみます。
  • さまざまなエンジンで「AddEventListener」アプローチをチェックした人はいますか?
于 2012-03-13T13:05:53.767 に答える
11

すべてのインライン イベント ハンドラを含む.setAttribute ()を使用して IE で設定できない属性の大きなコレクションがあります。

詳細はこちらをご覧ください:

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

于 2008-09-19T02:23:37.000 に答える
5

または、jQueryを使用して、これらすべての問題を回避することもできます。

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

jQueryは、すべてのクロスブラウザーの問題も処理します。

于 2009-07-01T17:14:34.377 に答える
5

これは、クロスブラウザー互換のイベント バインディングのための素晴らしい機能です。

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);

関数は次のとおりです。

// 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};
})();

このような大きな関数を使用したくない場合、これは IE を含むほとんどすべてのブラウザーで機能するはずです。

if (el.addEventListener) { 
    el.addEventListener('click', function, false); 
} else if (el.attachEvent) { 
    el.attachEvent('onclick', function); 
} 

クレイグの質問に答えて。新しい要素を作成し、古い要素の属性をコピーする必要があります。この関数は仕事をするべきです: ( source )

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;
}
于 2010-06-09T20:17:14.720 に答える
4

実際、私の知る限り、動的に作成されたインライン イベント ハンドラは、x.setAttribute()コマンドで作成された場合、Internet Explorer 8 内で完全に機能します。JavaScript コード内に適切に配置するだけです。ここであなたの問題(および私のもの)の解決策を見つけました。

すべてのステートメントをx.appendChild()正しい位置 (つまり、グループ内の最後の setAttribute コマンドの直後) に移動すると、すべての単一の setAttribute が想定どおりに IE8 で機能することがわかりました。 " と "type" 属性、および "onclick" イベント ハンドラ)。

これを実行する前に IE で取得したのは、画面全体にガベージ レンダリングが行われ、エラーが次々と発生したことだけだったので、これは非常に驚くべきことでした。さらに、すべての setAttribute が他のブラウザーでも同様に機能することがわかったので、この単純なコーディング方法を覚えていれば、ほとんどの場合問題なく使用できます。

ただし、HTML 要素が DOM に追加されると、IE では属性を変更できないため、その場で属性を変更する必要がある場合、このソリューションは機能しません。この場合、DOM から要素を削除し、要素とその属性を (もちろん正しい順序で) 再作成して、それらが適切に機能し、エラーをスローしないようにする必要があると想像します。

于 2013-09-24T19:34:31.887 に答える
3

関数をインラインで記述してください。インタプリタは、関数を記述していることを認識できるほど賢いです。このようにすると、それは単なる文字列であると想定されます(技術的にはそうです)。

于 2008-09-18T19:12:08.237 に答える
3
function CheckBrowser(){
    if(navigator.userAgent.match(/Android/i)!=null||
        navigator.userAgent.match(/BlackBerry/i)!=null||
        navigator.userAgent.match(/iPhone|iPad|iPod/i)!=null||
        navigator.userAgent.match(/Nokia/i)!=null||
        navigator.userAgent.match(/Opera M/i)!=null||
        navigator.userAgent.match(/Chrome/i)!=null)
        {
            return 'OTHER';
    }else{
            return 'IE';
    }
}


function AddButt(i){
    var new_butt = document.createElement('input');
    new_butt.setAttribute('type','button');
    new_butt.setAttribute('value','Delete Item');
    new_butt.setAttribute('id', 'answer_del_'+i);
    if(CheckBrowser()=='IE'){
        new_butt.setAttribute("onclick", function() { DelElemAnswer(i) });
    }else{
        new_butt.setAttribute('onclick','javascript:DelElemAnswer('+i+');');
    }
}
于 2013-02-17T15:31:39.263 に答える
2

場合によっては、ここにリストされている例が Internet Explorer でうまくいかなかったことがあります。

このようなメソッドでプロパティを設定する必要があるため(括弧なし)

HtmlElement.onclick = myMethod;

オブジェクト名やパラメーターを渡す必要がある場合は機能しません。Internet Explorer の場合、実行時に新しいオブジェクトを作成する必要があります。

HtmlElement.onclick = new Function('myMethod(' + someParameter + ')');

他のブラウザでも動作します。

于 2009-08-14T06:55:13.147 に答える
1

試しましたか:

    execBtn.setAttribute( "onclick"、function(){runCommand()});
于 2008-09-18T19:07:13.693 に答える
1

onclick の問題とは関係ありませんが、以下にも関連しています。

名前が JavaScript の予約語と衝突する html 属性の場合、別の名前が選択されます。<div class=''>、しかしdiv.className、または<label for='...'>、しかしlabel.htmlFor

まともなブラウザでは、これは影響しませんsetAttribute。したがって、gecko と webkit では を呼び出しますdiv.setAttribute('class', 'foo')が、IE では代わりに JavaScript プロパティ名を使用する必要があるため、div.setAttribute('className', 'foo').

于 2008-09-18T19:26:05.007 に答える
1

属性を設定するのではなく、イベント リスナーを検討しましたか? とりわけ、パラメーターを渡すことができます。これは、これを行おうとしたときに遭遇した問題でした。IE と Mozilla の場合は、2 回行う必要があります。

function makeEvent(element, callback, param, event) {
    function local() {
        return callback(param);
    }

    if (element.addEventListener) {
        //Mozilla
        element.addEventListener(event,local,false);
    } else if (element.attachEvent) {
        //IE
        element.attachEvent("on"+event,local);
    }
}

makeEvent(execBtn, alert, "hey buddy, what's up?", "click");

イベントに「クリック」や「マウスオーバー」などの名前を付けるだけです。

于 2009-03-13T14:19:29.693 に答える