开发者

Can 2 conditionals be combined like this?

开发者 https://www.devze.com 2023-02-15 12:26 出处:网络
I want to 1)display an alert if (\"#one\") is ch开发者_StackOverflowecked and (\"#two\") isn\'t checked. Then display a different alert if both are checked. What I have does the first part right, then

I want to 1)display an alert if ("#one") is ch开发者_StackOverflowecked and ("#two") isn't checked. Then display a different alert if both are checked. What I have does the first part right, then displays both alerts on the second part.

$("#one").click(function() {
    if($(this).is(":checked") && $("#two").is(":not(:checked)")) {
    alert("foo");
    } else {
        if($(this).is(":checked") && $("#two").is(":checked")) {
            alert("foo foo");
        }
    }
});


You're overcomplicating it, I think.

$("#one").click(function() {
    var thisIsChecked = this.checked,
        twoisChecked = $('#two').get(0).checked;

    if(thisIsChecked) {
         if (twoisChecked) {
            alert('foo foo');    //  <----
         }                       //      |  note the switch
         else {                  //      |
            alert('foo');        //  <----
         }
    }
});

See also: When to use Vanilla JavaScript vs. jQuery?


$("#one").click(function() {
    if(this.checked) {
       var $two = $("#two");
       if (!$two.is(":checked")) {
            alert("foo");
       } else {
            alert("foo foo");
       }
    }
});


It looks fine to me. Example of this in action here: http://jsfiddle.net/andypaxo/9vJGL/

Is this the behaviour that you want?


JSfiddle with solution

HTML:

<form>
   <input id="one" type="checkbox" />
   <input id="two" type="checkbox" />
</form>

JS:

var one = $("#one");
var two = $("#two");

one.click(function() {    
    if (one.is(":checked"))  {
        if (two.is(":checked")) {
           alert("foo foo"); 
        } else {
           alert("foo");
        }  
    }
});


I'd refactor a bit to get rid of the nested ifs and dry things up a bit:

$("#one").click(function() {
    if(!this.checked) { return }
    var message = $("#two").is(':checked') ? 'foo foo' : 'foo';
    alert(message)
});
0

精彩评论

暂无评论...
验证码 换一张
取 消