首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >jQuery循环步骤并添加html

jQuery循环步骤并添加html
EN

Stack Overflow用户
提问于 2017-01-10 06:34:35
回答 6查看 124关注 0票数 0

有办法简化下面的代码吗?当每个div被放入一个容器中时,代码就会下降。我只发布了我想简化的代码部分。我很感激在这方面的任何指导。

代码语言:javascript
复制
 if (count === 0) {
        $(".ernie").remove();
        $("#choices").append("<p class='ernie gone sr-only'>That was the last question</p>");
    }
    if (count === 1) {
        $(".ernie").remove();
        $("#choices").append("<p class='ernie sr-only'>There is 1 more question to select</p>");
    }
    if (count === 2) {
        $(".ernie").remove();
        $("#choices").append("<p class='ernie sr-only'>There are 2 questions to select</p>");
    }
    if (count === 3) {
        $(".ernie").remove();
        $("#choices").append("<p class='ernie sr-only'>There are 3 questions to select</p>");
    }
    if (count === 4) {
        $(".ernie").remove();
        $("#choices").append("<p class='ernie sr-only'>There are 4 questions to select</p>");
    }
    if (count === 5) {
        $(".ernie").remove();
        $("#choices").append("<p class='ernie sr-only'>There are 5 questions to select</p>");
    }
EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2017-01-10 06:41:36

代码语言:javascript
复制
var message = "";
message = (count === 0) ? 'That was the last question' : (count === 1 ? 'There is 1 more question to select' : 'There are '+ count +' questions to select');     
$(".ernie").remove();
$("#choices").append("<p class='ernie gone sr-only'>"+message+"</p>");
票数 1
EN

Stack Overflow用户

发布于 2017-01-10 06:40:54

代码语言:javascript
复制
$(".ernie").remove();
if (count) {
    $("#choices").append("<p class='ernie sr-only'>There " + (count > 1 ? "are" : "is") + " " + count + " more question" + (count > 1 ? "s" : "") + " to select</p>");
} else {
    $("#choices").append("<p class='ernie gone sr-only'>That was the last question</p>");
}

演示

票数 3
EN

Stack Overflow用户

发布于 2017-01-10 06:39:44

您可以使用switch语句代替,也可以在if语句之前删除.ernie (无论如何,您只是要删除它)。

您还可以将文本设置为附加到#choices,而不是每次输入文本,并附加到count的值上。

代码语言:javascript
复制
var text = "<p class='ernie sr-only'>There " + (count > 1 ? "are " : "is ") + count + " more question to select</p>";

$(".ernie").remove(); // remove ernie anyway
switch(count) {
    case 1: // if count is equal to 1
        $("#choices").append("<p class='ernie gone sr-only'>That was the last question</p>");
       break; 
    case 2: // if count is equal to 2
        $("#choices").append(text);
        break;
    // and so on...
    deafault: // if count is not equal to any of the above numbers
        void(0); // javascript for do nothing
        break;
}

希望能帮上忙!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41562529

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档