2012-03-05 20 views
0

を使用してイベントハンドラ関数を追加できません -私は次のJavaScriptコードを持っていたし、それが正常に働いていたのjQuery

var changeImageButton = document.getElementById("changeImageButton"); 
changeImageButton.onclick = buttonWasClicked; 

「buttonWasClicked」「はchangeImageButton」がクリックされたときに呼び出されるJavaScript関数の名前です。

今、JQueryを使用して同じコードを書きたいと思います。だから私は書いた -

$("#changeImageButton").attr("onclick","buttonWasClicked"); 

しかし、それは動作していません。私は間違って何をしていますか?

+0

を使用してこれを達成することができますが、魔法がないため、文字列を使用してに切り替えていることです明らかな理由。 –

+0

なぜなら、私はjQueryとJavaScriptをほとんど知っていないからです! – CodeBlue

+0

本を読んだことがありますか? –

答えて

4

あなたは間違って何いくつかの異なる方法

$("#changeImageButton").click(function(){ do_something(); }); 

$("#changeImageButton").on("click mouseover", function(){ do_something(); }); 
//this is useful because you can specify more than one event, if you want to 
//(so, this code would also trigger when you move the mouse over - not what 
// you want, but just for demonstration purposes) 

//In jQuery 1.7+ this is doubly useful, because this will also work with elements 
//added _after_ the DOM has initially loaded and this code has run 
+0

うわー。ありがとう。 – CodeBlue

2

jQueryには、クリックイベントを割り当てる方法があります。click()

$("#changeImageButton").click(buttonWasClicked); 
2

あなたは属性を追加し、イベントではなく登録する必要がありますクリック用

$('#changeImageButton').click(buttonWasClicked); 

jQueryのドキュメント:http://api.jquery.com/click/

+0

ありがとうございます。 – CodeBlue

1

はこれを試してみてください使っていますか?ここで

は、イベントリスナーを追加することでjQueryのチュートリアルです:http://api.jquery.com/click/

$("#changeImageButton").click(function() { 
    buttonWasClicked(); 
}); 
0

のjQueryのバージョンは何

$("#changeImageButton").click(buttonWasClicked); 
関連する問題