簡體   English   中英

如何改進我的代碼來實現'return false'?

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

我試圖在條件語句失敗后返回false。

我有

$('#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();
})​

我想只在id != $(this).attr('id).調用doSomething函數id != $(this).attr('id).

下面的代碼給了我想要的東西,但它看起來很難看。

$('#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();
    }
})​

任何人都有更好的方法嗎? 非常感謝!

切換到基本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();
})​

你不需要迭代thrue元素 ,你可以通過id和類來獲取它,比如#myId.myClass

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

如果您不介意不提前退出循環,可以使用jQuery filter

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

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

我認為你有什么是好的,但這避免了額外的條件:

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