jQuery 绑定方法无法按预期工作 [英] jQuery bind method does not work as expected

查看:33
本文介绍了jQuery 绑定方法无法按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无论是否选中,我都需要为选择下拉列表执行不同的操作!我尝试了这段代码,它在 JSFiddle 中正常工作,但它在我的项目中不起作用这是 WooCommerce 的结帐形式:

I need to perform different actions for a select dropdown if it is selected or not! I tried this code which is working correctly in a JSFiddle, but it doesn't work within my project which is a checkout form of WooCommerce:

jQuery(document).ready(function() {
  jQuery("#my_datepicker").bind('change', function() {
    if (jQuery(this).val() != "select") {
      alert('Something is selected!');
    } else {
      alert('Nothing is selected!');
    }
  });

  jQuery("#my_datepicker").trigger('change');
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<select name="my_datepicker" id="my_datepicker" class="select valid" data-placeholder="Please select" aria-invalid="false">
  <option value="select">Please select</option>
  <option value="11th December">11th December</option>
  <option value="12th December">12th December</option>
</select>

在我的项目中 alert('Nothing is selected!'); 按预期加载页面,但更改选择选项后什么也没有发生!即使我再次选择 ,它的相关警报也不会出现.你能指导我解决这个问题吗?

In my project alert('Nothing is selected!'); works on page load as expected but after changing select options nothing happens! Even when I choose <option value="select">Please select</option> again, it's related alert does not appear. Can you please guide me about this issue?

推荐答案

检查我希望它有效但如果此代码无效,这意味着您的网站出现了 js 错误,这就是为什么下面的 js 代码块会产生错误.

Check I hope it's working but If this code not working, it means js error coming on your site that's why the js code block below is error generating.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
jQuery(document).ready(function() {
    jQuery("#my_datepicker").trigger('change');
});
jQuery(document).on('change',"#my_datepicker", function(e) {
    e.preventDefault();
    if (jQuery(this).val() !== "select") {
      alert('Something is selected!');
    } else {
      alert('Nothing is selected!');
    }
});
</script>
<select name="my_datepicker" id="my_datepicker" class="select valid" data-placeholder="Please select" aria-invalid="false">
  <option value="select">Please select</option>
  <option value="11th December">11th December</option>
  <option value="12th December">12th December</option>
</select>

这篇关于jQuery 绑定方法无法按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆