0

onfocus() などのイベントに関連付けられた関数があり、場合によっては、デフォルト関数と 1 つ以上の追加関数を実行できるようにしたいと考えています。

したがって、元の関数を置き換えたくはありませんが、両方の関数が起動するように別の関数を追加したいと考えています。

<div id="mydiv" onfocus="alert('hello');">
if(something == somethingelse) $('#mydiv').onFocus += "alert('world');"

したがって、この例では、Hello だけが発火することもあれば、Hello と World の両方が発火することもあります。

例として onfocus() と alert() を使用していますが、これらは実際には私が定義した関数です。

これを行うにはどうすればよいですか?

4

6 に答える 6

0

jQuery を使用してフォーカス イベント ハンドラーを追加する

<script>
    $('#mydiv').on('focus', function(){
        //do soemthing
    })
</script>
于 2013-05-10T10:23:54.557 に答える
0

jQuery を使用してインライン イベント バインディングを使用しない場合は、代わりに次を使用します。

$("#mydiv").on("focus", function() {
    alert("hello");
});

// add one more action for the same event
$("#mydiv").on("focus", function() {
    alert("world");
});
于 2013-05-10T10:24:26.277 に答える
0

やったほうがいい

$('#myDiv').on('focus', function(){alert('world')});
于 2013-05-10T10:24:27.777 に答える
0
$('#mydiv').focus( function(){
})//This is for the elements which load while the page is loading

また

$('#mydiv').on('focus', function(){ 

 })  //This is for the elements which will load dynamically after the page load completed.
于 2013-05-10T10:24:31.243 に答える
0

jQuery を使用したくない場合は、これを試してください。純粋な JavaScript と同等です。

document.getElementById("mydiv").addEventListener("focus", function() { alert('world'); });

IE8以前と互換性を持たせたい場合は、試してみてください

var el = document.getElementById("mydiv");
if(el.addEventListener)
    el.addEventListener("focus", function() { alert('world'); });
else
    el.attachEvent("focus", function() { alert('world'); });
于 2013-05-10T10:24:33.543 に答える
0

jQuery を使用している場合は、on()インラインで指定するのではなく、イベント ハンドラーを要素にバインドするために使用します。

$('#mydiv').on('focus', function () {
    alert('hello');
});

$('#mydiv').on('focus', function () {
    if (something === somethingelse) {
        alert('world');
    }
});

または、この場合、1 つのハンドラー関数に結合することは合理的と思われます

$('#mydiv').on('focus', function () {
    alert('hello');

    if (something === somethingelse) {
        alert('world');
    }
});

これらをインラインで指定する場合、イベントにバインドできるイベント ハンドラーは 1 つだけなので、複数のイベント ハンドラーをバインドする場合は、1 つのイベント ハンドラーの制限を曲げてこれを処理するか、 DOMなどの別の方法を使用する必要があります。レベル 2 イベントまたはその上の抽象化 (jQuery のon()関数など)。

ハンドラーをバインドする要素が DOM に存在する場合、イベント ハンドラーをバインドする必要があります。これを行うには、jQuery のready()関数を使用できます。

// bind an event handler to the "ready" event on the document
$(document).ready(function () { 
    // ..... here 
});

または略記

$(function () { 
    // ..... here 
});
于 2013-05-10T10:24:45.730 に答える