jQuery的变更和负载解决方案 [英] jQuery on change and on load solution

查看:135
本文介绍了jQuery的变更和负载解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试简化一些我认为有点草率的代码.基本上是一个脚本,该脚本检查以查看选择框的值,并根据所选值显示或隐藏div.我想检查负载以及更改时的值.有没有更清洁的方法可以做到这一点?

I am trying to stream-line some code that I believe is a little sloppy. Basically a script that checks to see the value of a select box and shows or hides a div based on the value selected. I want to check the value on load as well as on change. Is there a cleaner way to do this?

// Required items  
 $(document).ready(function(){  
 if($("#credentials").attr("selectedIndex") == "None") {
    $('#CDiv').show();
 }else{
     $('#CDiv').hide();
   }
 $("#credentials").change(function(){
    if ($(this).val() == "None" ) {
        $('#CDiv').show();     
    } else {
        $('#CDiv').hide();      
        }  
    });    
});

我对此表示感谢.我仍然对jQuery有点绿色.谢谢!

I appreciate any help with this. I am still a little green on jQuery. Thanks!

推荐答案

selectedIndex是属性而不是属性,并且不会返回无".如果要读取它的值,则应改用prop方法.话虽如此,您可以触发更改事件,而不用使用if语句.通过触发事件,您的change处理程序将在DOM准备就绪时执行一次:

selectedIndex is a property not an attribute and it doesn't return "None". If you want to read it's value you should use prop method instead. That being said you can trigger the change event instead of using if statement. By triggering the event your change handler is executed once on DOM ready:

$("#credentials").on('change', function() {
    $('#CDiv').toggle( this.value === 'None' ); 
}).change();

这篇关于jQuery的变更和负载解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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