如何在更改和页面加载时获取选项值? [英] How to get option value on change AND on page load?

查看:101
本文介绍了如何在更改和页面加载时获取选项值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道可以在两种功能中进行操作,但是我不确定如何在一种功能中使用它.

I know that it is possible to do in two functions, but I am not sure how to make it in one.

$("#purchase_sub_type").change(function() {
   if($(this).val() == 15) {
       console.log('is 15');
   }
   else {
      console.log('not 15');
   }
});

这是示例代码.问题在于此代码仅在更改时有效,而在重新加载页面上从DB加载值时则无效.有简单的方法可以将当前val添加到此函数吗?我知道可以添加另一个功能,但是那样代码会变得很丑陋并重复执行.

This is example code. Problem is that this code works only on change, not when value is loaded form DB on page reload. Is there simple way to add current val to this function? I know that it is possible adding another function, but in that way code gets ugly and repeats.

推荐答案

触发更改事件,以便代码触发

Trigger the change event so the code fires

$("#purchase_sub_type").change(function() {
   if($(this).val() == 15) {
       console.log('is 15');
   }
   else {
      console.log('not 15');
   }
}).change();  //or .trigger("change");

这篇关于如何在更改和页面加载时获取选项值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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