【问题标题】:Append comma (,) plus html if td has any text otherwise append only html如果 td 有任何文本,则附加逗号 (,) 加上 html,否则仅附加 html
【发布时间】:2015-01-22 15:19:54
【问题描述】:

我正在编写一些 jQuery 代码,但我有一些疑问。这是我到现在为止的:

var html = '';
data.entities.forEach(function (value, index, array) {
    html += index !== data.entities.length-1 ? value.pais + ', ' : value.pais;
});

var rowUpdate = $('#distribuidorBody').find('#td-' + data.idToUpdate);
rowUpdate.text() !== "" ? html += ', ' + html : html;
rowUpdate.append(html);

大想法:我可以多次执行相同的代码,所以第一次 rowUpdate 没有任何值,所以 text() 是空的,我会得到一些 HTML 输出,例如:Country1, Country2, Country3 和依此类推,然后rowUpdate.text() 应该是Country1, Country2, Country3。因此,如果我第二次运行相同的代码并添加Country4, Country5,那么rowUpdate.text() 应该是Country1, Country2, Country3, Country4, Country5。我的代码对吗?如果没有任何帮助?我没有收到错误,但我需要了解我所做的是对还是错。我也想知道这段代码的作用:

rowUpdate.text() !== "" ?: html += ', ' + html;

它不是我的,我在它周围看到它,但不知道它的作用。

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    forEach 的替代品可以是 map

    var text = data.entities.map(function(v){ return v.pais }).join(', ');
    

    reduce:

    var text = data.entities.reduce(function(a, b){ return {pais: a.pais +', '+ b.pais}}).pais;
    

    对于三元运算符,您需要两个表达式:condition ? expr1 : expr2 MDN

    var rowUpdate = $('#distribuidorBody').find('#td-' + data.idToUpdate);
    text = (rowUpdate.text() !== "") ? ', ' + text : text;
    // alternative with if
    // if(rowUpdate.text() !== "") text = ', ' + text ;
    rowUpdate.append(text);
    

    更新:在每个值上添加span

    var text = data.entities.map(function(v){ return '<span class="countryToDelete">' + v.pais + '</span>'  }).join(', ');
    

    【讨论】:

    • 这个答案是最好的+1。这就是I'd do it。对于 OP - 不要附加 span class 并且不要基于 $("#id-" +text 找到 - 这些都很可怕 - 您正在查询表示层的业务逻辑。而是将项目存储在一个数组中,并为每个项目添加点击处理程序。映射到元素,然后将处理程序附加到它们 - 而不是字符串。保留对行元素本身的引用,而不是用来选择它的选择器。
    【解决方案2】:

    一个可能更好的解决方案是建立一个您想要显示的项目数组,然后使用.join(', ') 创建文本:

    var items = [];
    data.entities.forEach(function (value, index, array) {
        items.push(value.pais);
    });
    var displayText = items.join(', ');
    $('#distribuidorBody').find('#td-' + data.idToUpdate).html(displayText);
    

    现在,最后一行,因为'#td-' + data.idToUpdate 是一个ID,它应该是页面唯一的(如果不是,你应该让它如此)。如果或一旦这是真的,您可以将其缩短为

    $('#td-' + data.idToUpdate).html(displayText);
    

    【讨论】:

    • 如果我有我在帖子中提到的以前的文字怎么办?它将被保留还是将被覆盖?还在想,现在我需要在数组上的每个项目上附加一些&lt;span class="countryToDelete"&gt;&lt;/span&gt;,因为稍后我将允许通过单击每个项目来删除它们,如何?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多