なぜ、onclickプロパティセットとのsetAttributeが入っているか確認してくださIE?

StackOverflow https://stackoverflow.com/questions/95731

  •  01-07-2019
  •  | 
  •  

質問

走り込んだこの問題は本日投稿したり、場合には他の誰かが同じ問題です。

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

がんの家に行onclick、動的に生成要素を使用できませんのsetAttribute.その代わりに、設定する必要性onclickのオブジェクトと匿名の機能包装のコードしたいのです。

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

悪いアイデア:

できない

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

で休憩の家は非標準モードによると@scunliffe.

できない。

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

で実行すぐに、設定した結果、runCommand(することによって、これらのonClick属性値もお願いできますか

execBtn.setAttribute("onclick", runCommand);
役に立ちましたか?

解決

この作品の両方FF、IEで書き方


    button_element.setAttribute('onclick','doSomething();'); // for FF
    button_element.onclick = function() {doSomething();}; // for IE

感謝 このポスト.

更新:このことを実証するもので を使用する必要setAttribute!このメソッドの動作が必要な場合は、独自のonclick属性からのHTML追加し、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
}

他のヒント

があり 属性のコレクションす まる事が出来ませんの家 を使用 .setAttribute() るキャンパスの中心に位置すインラインイベントハンドラです。

募集要項など詳細はこちら。

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

作品!

両方使いないようにする必要は全くなされ

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

う作品毎に現在のブラウザです。

試験電流Firefox、Safari、データの再活用やホームページChrome Windows;Firefox 係Ubuntu;試験は行っておりませんMacまたはモバイルシステム。

  • クレイグ:私が"書きします。getElementById(ID).type='パスワード';
  • では"AddEventListener"アプローチの異なるエンジン?

これは素晴らしい機能のためのクロスに対応したブラウザのイベントに結合する。

わかったから 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); 
} 

対応クレイグの質問です。おいて新しい要素をコピー以上の属性の古い要素になります。この機能は?:()

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

またはを使用できるjQueryを回避すべての問題:

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

jQueryのままのクロスブラウザの問題です。

実は、私が知る限りでは動的に作成したインラインイベントハンドラから完全に内Internet Explorer8時作成された x.setAttribute() コマンドすぐに位置して適切な内でJavaScriptのコードです。私の解決の問題(鉱) こちらの.

時の移動の諸表を含む x.appendChild() その正しい位置(終了後のsetAttributeコマンドグループ内で知られる単一のsetAttributeたIE8ということで、全ての形で入力属性を含む"名""タイプ"属性、そして"onclick"イベントハンドラー).

そしても著しく、てんの家の前にいったゴミの描画されるには、画面一の場でもあります。また、これらの毎setAttributeいたのその他のブラウザなどの場合とを覚えておいてくださいこの簡単なコーディング-実践できるでしょういくことが多いです。

しかし、このソリューションが成り立たないと思う場合は変更属性には、その変更はできませんの家は、HTMLの要素に追加されDOM;この場合、このとの違いによって削除の要素からDOMを再現し、その属性の正しい順序です。) て正常に動作し、をスローしません。

書き機能をインラインの通訳がスマートだけだけを書く機能です。いうことではなく文字列(あるいは技術的にすべき水準にあるといえます。

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+');');
    }
}

ってみます:

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

場合の例をここに記載のか私にとってインターネット以下のように変更しました。

くためのプロパティを設定方法によりこのようなブラケット)

HtmlElement.onclick = myMethod;

でない場合は運行しない場合はオブジェクト名やパラメータ。のためのInternet Explorerできるようにする必要があります新しいオブジェクトにランタイム:

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

作品もその他のブラウザを推奨いたします。

は関係ありませんのonclickの問題にも関連:

Html属性の名前衝突とjavascriptの予約語では、代替名が選択されたもので、例えば. <div class=''>, ものの、 div.className, や <label for='...'>, ものの、 label.htmlFor.

リーズナブルブラウザに影響しません setAttribute.ではトカゲとwebkitんの電話 div.setAttribute('class', 'foo'), がIE使用にはjavascriptのプロパティ名ではなく、 div.setAttribute('className', 'foo').

いま考えるイベントリスナーにより設定の属性?その他のものですパスのパラメータ問題になったそうではないかと思います。だい二家やMozilla:

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

うイベント名様"をクリックし"または"mouseover".

私はこれを取得します、私の場合いを入力'要素をいただくこともできました画像がたに設定"onclick属性のためにこのイメージと同じ体験を課題であり、またラッピングイメージ"、"要素の参照ポイント機能のようです。

var rowIndex = 1;
var linkDeleter = document.createElement('a');
linkDeleter.setAttribute('href', "javascript:function(" + rowIndex + ");");

var imgDeleter = document.createElement('img');
imgDeleter.setAttribute('alt', "Delete");
imgDeleter.setAttribute('src', "Imagenes/DeleteHS.png");
imgDeleter.setAttribute('border', "0");

linkDeleter.appendChild(imgDeleter);

してみてください execBtn.onclick=function(){eval('runCommand()')};

私にとっています。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top