简体   繁体   English

如何改进我的代码来实现'return false'?

[英]How to improve my codes to implement 'return false'?

I am trying to return false after a conditional statement fail. 我试图在条件语句失败后返回false。

I have 我有

$('#btn').click(function() {
    $('.title').each(function() {
        if (id == $(this).attr('id')) {
            alert('The name already exists.')
            return false; //I hope my codes would stop here if condition is true
        }
    })
    // my codes still call the doSomething function even if the conditional         
    //statement is true
    doSomething();
})​

I want do call the doSomething function ONLY if id != $(this).attr('id). 我想只在id != $(this).attr('id).调用doSomething函数id != $(this).attr('id).

The codes below gave me what I want but it seems ugly. 下面的代码给了我想要的东西,但它看起来很难看。

$('#btn').click(function() {
    var nameExist = false
    $('.title').each(function() {
        if (id == $(this).attr('id')) {
            alert('The name already exists.')
            nameExist = true;
            return false; //I hope my codes would stop here if condition is true
        }
    })
    if (!nameExist) {
        doSomething();
    }
})​

Anyone has a better approach for this? 任何人都有更好的方法吗? Thanks a lot! 非常感谢!

Switch to a basic for loop. 切换到基本for循环。

$('#btn').click(function() {
    var elements = $(".title");
    for (var i = 0; i < elements.length; i++) {
        if (id == elements[i].id) {
            alert('The name already exists.')
            return false; //I hope my codes would stop here if condition is true
        }
    }

    doSomething();
})​

You don't need to iterate thrue the elements , you can get it by the id and class like, #myId.myClass . 你不需要迭代thrue元素 ,你可以通过id和类来获取它,比如#myId.myClass

$('#btn').click(function() {
    if($('#' + id + '.title').length) {
        alert('The name already exists.');
    } else {
        doSomething();
    }
});

If you don't mind not exiting the loop early, you can use jQuery filter 如果您不介意不提前退出循环,可以使用jQuery filter

$('#btn').click(function(){
    var itensWithSameName = $('.title').filter(function(){
      return id == $(this).attr('id');
    })

    if(itensWithSameName.size() > 0)
        alert('The name already exists.');
});

I think what you have is fine, but this avoids the extra conditional: 我认为你有什么是好的,但这避免了额外的条件:

var func = doSomething;
...
if (id == $(this).attr('id')) {
   func = $.noop;
...

func();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM