如果声明,如何重构?

时间:2016-08-01 16:09:37

标签: javascript jquery refactoring

我有一个很长的if语句,我想要重构。该语句侦听单击,然后根据这些文本框中是否包含任何内容更新五个文本框中的一个。我怎样才能更改我的代码以提高效率。

$('#img1').click(function() {
if ($('#card1').val().length === 0) {
    $('#card1').val('A feeling of warmth');
} else if ($('#card2').val().length === 0)  {
    $('#card2').val('A feeling of warmth');
} else if ($('#card3').val().length === 0){
  $('#card3').val('A feeling of warmth');
} else if ($('#card4').val().length === 0){
  $('#card4').val('A feeling of warmth');
} else if ($('#card5').val().length === 0){
  $('#card5').val('A feeling of warmth');
}

});

4 个答案:

答案 0 :(得分:6)

你可以使用循环

$('#img1').click(function() {
    var items = ["#card1", "#card2", "etc"];
    for(var i=0;i<items.length;i++){
        if ($(items[i]).val().length === 0) {
            $(items[i]).val('A feeling of warmth');
        }
    }
});

它至少更容易阅读。此外,如果你的按钮总是卡+数字,你可以使它更简单(不易阅读,只需更少的线路和维护)

$('#img1').click(function() {
    for(var i=0;i<=5;i++){
        if ($("#card" + i).val().length === 0) {
            $("#card" + i).val('A feeling of warmth');
        }
    }
});

答案 1 :(得分:1)

好像你正在使用JQuery。您可以使用选择器和过滤器来隔离第一个空项:

&#13;
&#13;
for d in devices:
    pd = DeviceConfigPush(d.task_info)
    subtasks.append(pd.s(task_info))

master = MasterConfigPush()
ch = chord(header=subtasks, body=master.s().set(link_error=['push_ssh_task_master']))
ch.delay()
&#13;
$('#img1').click(function() {
  $('input:text[id^=card]')
    .filter(function() { return $(this).val() == ""; })
    .first()
    .val('A feeling of warmth');
});
&#13;
&#13;
&#13;

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="img1">CLICK ME</button><br> <input id="card1"><br> <input id="card2"><br> <input id="card3"><br> <input id="card4"><br> <input id="card5">选择ID以&#39; card&#39;开头的所有文字输入。但同样的原则也适用于其他元素类型。

答案 2 :(得分:0)

$('#img1').click(function() {
// num can be total count of the element like $(.card).children.count
var num = 5, // preferably dont make it hardcoded.
    str = 'A feeling of warmth',
    preIdStr = '#card',
    id;
for (var i = 1; i <= num; i += 1) {
    id = preIdStr + i;
    if ($(id).val().length === 0) {
        $(id).val(str);
    }
}

});

答案 3 :(得分:0)

为所有卡片提供相同的class。 然后使用选择器$('.yourclass')

现在使用jQuery for-each(.each)函数迭代所有元素。在循环中,您检查值,将其设置为您想要的任何值,并在设置值时返回false,因为此退出是循环。

$('.yourclass').each(
    function () {
        if (this.val().length === 0) {
            this.val('your value');
            return false; // exit loop
        }
    });
相关问题