繁体   English   中英

如何使用jQuery更改onChange事件的调用函数

[英]How Change calling function of onChange event using jQuery

我有这段代码可以在html的div标签中显示下拉列表。 在此,我为通过jQuery的下拉菜单设置了一个函数“ hello()”,但问题是它未调用该函数。

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

你需要这个。

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

编辑:

万一您在所有几乎完全相同的答案中都错过了它,最初的问题是您将函数放在引号"hello()"而不仅仅是使用函数名称来调用它(即hello )...

您只需要将其包装在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");
    }
}); 

使用.change()

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

还要将其包装在jquery init函数中,以确保在DOM完全加载后运行:

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

我建议您搬家:

$("#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"));
});

这将允许页面加载,然后更改属性。

您正在使用jQuery。 大多数事情都有捷径。 它应该是:

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

要么

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

它也应该在文档准备功能中。 这样一来,它就不会尝试在元素存在之前附加事件。

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

我不能发表评论,但正如其他人所说。 问题是您正在使用$("#sel").attr("onchange", "hello()"); 而不是$("#sel").attr("onchange", hello);

这是因为在JavaScript中,函数是数据类型。 因此,您必须使用高阶函数

如果您想更好地理解这一点,建议您学习函数式编程。

除此之外,您应该使用jQuery方法添加事件侦听器。 在这种情况下$(.'#sel').change(hello);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM