【问题标题】:jQuery how to remove the comma before first element?jQuery如何删除第一个元素之前的逗号?
【发布时间】:2013-12-03 02:32:53
【问题描述】:

我正在使用 jQuery push() 获取一个数组。但是在第一个元素之前有一个逗号。我需要第一个元素没有逗号的数组(其余元素需要逗号)。有什么想法吗?

谢谢

function delImg(newThis){
    $(newThis).parent().hide();
    var Id = $(newThis).siblings('.hidden').html();
    Ids.push(Id);
    alert(Ids);
    return Ids;

}

【问题讨论】:

    标签: javascript jquery arrays push comma


    【解决方案1】:

    您正在向数组添加一个空元素,因此您在开始时会得到,

    function delImg(newThis) {
        $(newThis).parent().hide();
        var Id = $(newThis).siblings('.hidden').html();
        if ($.trim(id) !== '') { //push to array if id value is not empty
            Ids.push(Id);
        }
        alert(Ids);
        return Ids;
    }
    

    【讨论】:

    • 你需要对 Id 的 HTML 进行 .trim() 处理。
    • @writeToBhuwan 先生,但我正在使用$.trim()
    【解决方案2】:
    function delImg(newThis) {
        $(newThis).parent().hide();
        var Id = $(newThis).siblings('.hidden').html().trim();
        if (Id !== '') {
            Ids.push(Id);
        }
        alert(Ids);
        return Ids;
    }
    

    【讨论】:

    • 但第 0 个元素仍未定义。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-17
    • 2019-03-19
    相关资源
    最近更新 更多