javascript - 如何改进我的代码以实现 'return false'?

标签 javascript jquery

我试图在条件语句失败后返回 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 函数

下面的代码给了我想要的东西,但看起来很难看。

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

关于javascript - 如何改进我的代码以实现 'return false'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13940618/

相关文章:

jquery - .valid() 仅使用 jQuery 验证插件验证第一个输入

Jquery Remove() 不删除选定的节点

php - WordPress 子主题包括包含文件

javascript - 单击时更改内部 html,然后使用 Jquery 或 JS 更改回单击

javascript - 为什么htmlunit的结果和chrome的结果不一样?

javascript - 在 easelJS 中将文本居中放置在矩形内

javascript - 如何在不使用科学计数法的情况下显示 "toPrecision"的结果?

javascript - 添加模态图像?

javascript - 用于格式化电子表格的 Google 脚本制作工具

javascript - 如何获取子节点的父节点