简体   繁体   English

更改未触发翻转切换开关(jQuery)

[英]Flip toggle switch (jQuery) on change not firing

I need to fire an event (which sends POST data to an external script) when the state of a toggle switch changes, but I cannot even get the most basic example to work... 当切换开关的状态更改时,我需要触发一个事件(该事件将POST数据发送到外部脚本),但是我什至无法获得最基本的示例来工作...

Can someone please tell me what I am doing wrong? 有人可以告诉我我做错了吗?

HTML: HTML:

<label for="flipswitch">Option:</label>
<select name="flipswitch" id="flipswitch" data-role="slider">
    <option value="off">Off</option>
    <option value="on">On</option>
</select>`

JavaScript (in the <head> section): JavaScript(在<head>部分中):

<script>

    $('#flipswitch').change(function(){
        console.log("flipswitch");
    });
</script>

The code works for me. 该代码对我有用。 Are you sure you're looking at the console output? 您确定要查看控制台输出吗? Do you have the code in the $('document').ready(function() { 您是否在$('document')。ready(function(){

)}; )};

The problem you are experiencing is that at the execution time of script, there is no element with the specified id. 您遇到的问题是在脚本执行时,没有具有指定ID的元素。 There are several ways how to overcome this problem. 有几种方法可以解决此问题。

<script>

    $(function() {
        $('#flipswitch').change(function(){
            console.log("flipswitch");
        });          
    });
</script>

or you may simply move the script tag from head tag to the bottom of body tag and it will work as well. 或者您也可以将script标签从head标签移到body标签的底部,它也可以正常工作。

$("#flipswitch").on("change", function(e){
    console.log("flipswitch");
});

Could be because the .change is deprecated in favor of .on() 可能是因为不建议使用.change,而建议使用.on()

DEMO: http://jsfiddle.net/naUmA/13/ 演示: http : //jsfiddle.net/naUmA/13/

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

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