2012-03-29 136 views
2

我有這個代碼可以顯示在HTML的div標籤下拉。在這裏,我已經設置了一個函數「hello()」來通過jquery下拉菜單,但問題在於它沒有調用該函數。如何更改使用jQuery的onChange事件的調用函數

<body> 
<div id="content"></div> 
<script src="http://code.jquery.com/jquery-latest.js"></script> 
<script type="text/javascript"> 

    $("#content").append('<select id="sel" onchange="fly()"><option value="1">Choose Me</option></select>'); 
    $("#sel").attr("onchange", "hello()"); 
    alert($("#sel").attr("onchange")); 

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

    function fly() { 
     alert("Go to fly"); 
    } 
</script> 
</body> 

回答

1
$("#sel").attr("onchange", hello); 

編輯:

如果你錯過了它在所有的近乎相同的答案,原來的問題是,你把引號"hello()",而不是僅僅使用功能名稱來調用函數它(即hello)...

0

你只需要包裝在一個jQuery初始化

$(function(){ 
    $("#content").append('<select id="sel" onchange="fly()"><option value="1">Choose Me</option></select>'); 
    $("#sel").attr("onchange", "hello()"); 
    alert($("#sel").attr("onchange")); 

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

    function fly() { 
     alert("Go to fly"); 
    } 
}); 
0

使用.change()

$("#sel").change(function(){ 
    hello(); 
}); 

此外,敷在jQuery的初始化函數,以確保其追着DOM完全加載:

$(function(){ 
    $("#content").append('<select id="sel" onchange="fly()"><option value="1">Choose Me</option></select>') 
    $("#sel").change(function(){ 
     hello(); 
    }); 
}); 
+0

這將執行hello函數,並將返回值(undefined)傳遞給change()。 – Jivings 2012-03-29 15:51:36

+0

@Jivings更新回答 – Curt 2012-03-29 15:52:41

0

我建議你動:

$("#content").append('<select id="sel" onchange="fly()"><option value="1">Choose Me</option></select>'); 
$("#sel").attr("onchange", "hello()"); 
alert($("#sel").attr("onchange")); 

轉換爲文件準備就緒功能並刪除" s約爲hello,如下所示:

$(document).ready(function() { 
    $("#content").append('<select id="sel" onchange="fly()"><option value="1">Choose Me</option></select>'); 
    $("#sel").attr("onchange", hello); 
    alert($("#sel").attr("onchange")); 
}); 

這將允許頁面加載,然後更改屬性。

0

您正在使用jQuery。大多數事情都有一個捷徑。它應該是:

var hello = function() { 
    alert("Hello"); 
} 
$("#sel").change(hello); 

$("#sel").change(function() { 
alert("Hello"); 
}); 

這也應該是在文件準備好功能。這是因爲它不會在元素存在之前嘗試附加事件。

$(document).ready(function() { 
    // code here 
}); 
0

我不能評論,但正如其他人所說。您使用的問題是$("#sel").attr("onchange", "hello()");而不是$("#sel").attr("onchange", hello);

這是因爲在JavaScript中,函數是數據類型。所以你必須使用high order functions

如果你想更好地理解,我建議學習函數式編程。

除此之外,您應該使用jQuery方法添加事件偵聽器。在這種情況下,$(.'#sel').change(hello);

相關問題