javascript jQuery 触发器更改事件不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22390339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:03:10  来源:igfitidea点击:

jQuery trigger change event doesn't work

javascriptjqueryeventswebtriggers

提问by stowka

I'm having an issue with my JavaScript code, I want to fire a change event when I load the page, it used to work in local but now it's online and nothing happens.

我的 JavaScript 代码有问题,我想在加载页面时触发更改事件,它曾经在本地工作,但现在在线并且没有任何反应。

Here's my code: (there's some php code, it works fine)

这是我的代码:(有一些 php 代码,它工作正常)

$("#city").change(function() {
    console.log("city changed...");
    var city = $( "#city option:selected" ).val();
    $.get(
        "ajax.php",
        {
            page: "venues",
            city: city
        },
        function (data) {
            $("#venue").empty();
            $("#venue").append('<option selected disabled>--</option>');
            for(var i = 0; i < data.venues.length; i+=1) {
                if (data.venues[i].id == <?php print $concert->getVenue()->getId(); ?>) {
                    $("#venue").append('<option value="'+data.venues[i].id+'" selected>'+data.venues[i].name+'</option>');
                } else {
                    $("#venue").append('<option value="'+data.venues[i].id+'">'+data.venues[i].name+'</option>');
                }
            }
            $("#label-venue").visible();
            $("#venue").visible();

            /*if (controlForm())
                $("#submit").removeProp("disabled");
            else
                $("#submit").addProp("disabled");*/
        }
    );
});

$("#country").change(function() {
    console.log("country changed...");
    var country = $( "#country option:selected" ).val();
    $("#country-city").html($( "#country option:selected" ).html());
    $.get(
        "ajax.php",
        {
            page: "cities",
            country: country
        },
        function (data) {
            $("#city").empty();
            $("#city").append('<option selected disabled>--</option>');
            $("#venue").empty();
            $("#venue").append('<option selected disabled>--</option>');
            for(var i = 0; i < data.cities.length; i+=1) {
                if (data.cities[i].id == <?php print $concert->getVenue()->getCity()->getId(); ?>) {
                    $("#city").append('<option value="'+data.cities[i].id+'" selected>'+data.cities[i].name+'</option>');
                } else {
                    $("#city").append('<option value="'+data.cities[i].id+'">'+data.cities[i].name+'</option>');
                }
            }
            $("#label-city").visible();
            $("#city").visible();
            $("#city").trigger("change");
        }
    );
});

function init() {
    $.get(
        "ajax.php",
        {
            page: "countries"
        },
        function (data) {
            $("#country").empty();
            $("#country").append('<option selected disabled>--</option>');
            for(var i = 0; i < data.countries.length; i+=1) {
                if (data.countries[i].id == <?php print $concert->getVenue()->getCity()->getCountry()->getId(); ?>) {
                    $("#country").append('<option value="'+data.countries[i].id+'" selected>'+data.countries[i].name+'</option>');
                } else {
                    $("#country").append('<option value="'+data.countries[i].id+'">'+data.countries[i].name+'</option>');
                }
            }
            $("#country").trigger("change");
        }
    );
}

$("#country-dismiss").click(function() {
    $("#country-name-en").val("");
    $("#country-name-nl").val("");
    $("#country-name-de").val("");
});

$("#city-dismiss").click(function() {
    $("#city-name-en").val("");
    $("#city-name-nl").val("");
    $("#city-name-de").val("");
});

$("#venue-dismiss").click(function() {
    $("#venue-name").val("");
    $("#venue-texte").val("");
    $("#venue-website").val("");
});

$("#country-submit").click(function() {
    console.log("adding country");
    var name_en = $("#country-name-en").val();
    var name_nl = $("#country-name-nl").val();
    var name_de = $("#country-name-de").val();

    $.post(
        "ajax.php?page=add_country",
        {
            en: name_en,
            nl: name_nl,
            de: name_de
        },
        function (data) {
            init();
            console.log(data);
        }
    );

});

$("#city-submit").click(function() {
    var name_en = $("#city-name-en").val();
    var name_nl = $("#city-name-nl").val();
    var name_de = $("#city-name-de").val();
    var country = $( "#country option:selected" ).val();

    $.post(
        "ajax.php?page=add_city",
        {
            country: country,
            en: name_en,
            nl: name_nl,
            de: name_de
        },
        function (data) {
            $("#country").trigger("change");
        }
    );
});

$("#venue-submit").click(function() {
    var name = $("#venue-name").val();
    var address = $("#venue-address").val();
    var website = $("#venue-website").val();
    var city = $( "#city option:selected" ).val();

    $.post(
        "ajax.php?page=add_venue",
        {
            city: city,
            name: name,
            address: address,
            website: website
        },
        function (data) {
            $("#city").trigger("change");
        }
    );
});

$( document ).ready(function() {
    (function($) {
        $.fn.invisible = function() {
            return this.each(function() {
                $(this).css("visibility", "hidden");
            });
        };
        $.fn.visible = function() {
            return this.each(function() {
                $(this).css("visibility", "visible");
            });
        };
    }(jQuery));
    init();
});

I hope someone will be able to see where I'm making a mistake (or several). Thanks!

我希望有人能够看到我犯了一个错误(或几个)。谢谢!

采纳答案by user3417400

You could avoid the usage of $().triggerby defining the functions to be used as event handlers in the global namespace (or in a wrapper function if you're worried about adding properties to the global object).

您可以$().trigger通过在全局命名空间(或者如果您担心向全局对象添加属性的情况下在包装函数中)定义要用作事件处理程序的函数来避免使用。

Add the event handler by naming the funciton you defined, and when you need to trigger the event handler you just invoke that function.

通过命名您定义的函数来添加事件处理程序,当您需要触发事件处理程序时,您只需调用该函数。

I'll give you an example:

我给你举个例子:

function countryChange () {
  ...
}

$('#country').on('change', countryChange);

function init() {
  ...
  countryChange(); 
}

$(document).ready(function () {
  init();
}

回答by emrhzc

You have to put your change events inside the callback function of $(document).ready(), anywhere before where you trigger them.

您必须将更改事件放在 $(document).ready() 的回调函数中,在触发它们之前的任何位置。

 $(document).ready(function(){

     $(selector).change(function(){
           ...
     });

     $(selector).trigger("change"); //or $(selector).change();

 });
 $(document).ready(function(){

     $(selector).change(function(){
           ...
     });

     $(selector).trigger("change"); //or $(selector).change();

 });

I strongly recommend to never bind your selectors outside the ready event.

我强烈建议永远不要在就绪事件之外绑定您的选择器。

回答by Alireza Ahmadi Rad

My problem got solved after I placed $(selector).trigger("change"); in $(document).ready() function. My whole document was being created by JS.

放置 $(selector).trigger("change"); 后我的问题就解决了。在 $(document).ready() 函数中。我的整个文档都是由 JS 创建的。

回答by user583576

$( ".target" ).change(function() {
    alert( "Handler for .change() called." );
});