jQuery的change事件在页面加载时未触发,我该如何修复它?

huangapple go评论53阅读模式
英文:

jQuery change event not firing on page load, how can I fix it?

问题

这是您的代码:

$awaySelect = $('#awayID');

$awaySelect.change(function(){
      alert('hi'); 
      var awayData = $(this).val();
      if(awayData == 202 || awayData == 203){ 
            $('.gameToshowAway').show(); 
            $('.gameToshowAway').css('display','inline-block');
            $("#gameDate3").prop('disabled',false); 
            $('.gamedatecolor1').css('display','inline-block'); 
            $('.positionToDisplayAway').hide();                   
        } else {
        	$('#unknownWell').hide();
            $('.gameToshowAway').hide();           
        } 

        if(awayData == 204) {
            $('.gameToshowAway').hide();  
            $('#unknownWell').hide();
            $('.positionToDisplayAway').css('display','inline-block');          
        }
    }).trigger('change');

请注意,我已经将你的代码中的##改为了#,因为ID选择器应该使用单个#。另外,我将.trigger()的参数改为了'change'以触发change事件。

希望这对您有所帮助,如果还有其他问题,请随时提出。

英文:

I have a code which is used in both purpose, even on click of any other button and even while editing, it should do on page load

Here is my code


$awaySelect = $('##awayID');

$awaySelect.change(function(){
      alert('hi'); 
      var awayData = $(this).val();
      if(awayData == 202 || awayData == 203){ 
            $('.gameToshowAway').show(); 
            $('.gameToshowAway').css('display','inline-block');
            $("##gameDate3").prop('disabled',false); 
            $('.gamedatecolor1').css('display','inline-block'); 
            $('.positionToDisplayAway').hide();                   
        } else {
        	$('##unknownWell').hide();
            $('.gameToshowAway').hide();           
        } 

        if(awayData == 204) {
            $('.gameToshowAway').hide();  
            $('##unknownWell').hide();
            $('.positionToDisplayAway').css('display','inline-block');          
        }
    }).trigger();

but it not doing any alert even i had the trigger at the bottom to try to execute it on page load

what is wrong happening here

答案1

得分: 0

使用.change()而不带参数,或将事件名称传递给.trigger

$awaySelect.change(function(e) {
    // ...
}).change();
// 或者
$awaySelect.trigger('change');
英文:

Call .change() with no arguments or pass the event name to .trigger.

$awaySelect.change(function(e) {
    // ...
}).change();
// or
$awaySelect.trigger('change');

huangapple
  • 本文由 发表于 2023年6月1日 07:43:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76377891.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定