在javascript中返回HTML代码?

4

我对JavaScript还比较陌生,想知道如何让这段代码(作为整体的一部分)按照我的要求执行。我想在“购物车中的文章”和“购物车中的文章”短语中添加HTML。这可行吗?非常感谢。

我的意思不是样式(粗体或斜体),这是我想要它返回的内容:

return quantity + (quantity == 1 ? ' 
  article in shopping cart <span class="simpleCart_quantity"></span>- 
 <span class="simpleCart_total"></span>
 <a href="shoppingcart.html">Show</a>' : 
 ' articles in shopping  cart 
  <span class="simpleCart_quantity"></span>-
  <span class="simpleCart_total"></span>
  <a href="shoppingcart.html">Show</a>');

我知道这是不可能的,怎么可能呢?
quantity: function () {
    var quantity = 0;
    simpleCart.each(function (item) {
        quantity += item.quantity();
    });
    if (quantity == 0) {
        return 'Your shopping cart is empty';
    } else {
        return quantity + (quantity == 1 ? ' article in shopping cart' : ' articles in shopping cart');
    }
},

你是如何将返回值注入到DOM中的? - Gabriele Petrioli
1个回答

3
当然可以,不过调用该函数的任何东西是否对结果做出合理的处理是另一回事。无论如何,只需在需要的字符串中包含所需的HTML即可:
return quantity + (quantity == 1 ? ' article <span class="x">in shopping cart</span>' :
                                   ' articles <i>in</i> shopping cart');

编辑:你在问题中添加的示例无法正常工作,因为它存在语法错误——你的字符串文字包含换行符。使其成为有效字符串即可运行,可以将每个字符串放在一行上,也可以将单个字符串连接起来:

return quantity + (quantity == 1 ?  
  'article in shopping cart <span class="simpleCart_quantity"></span>- <span class="simpleCart_total"></span> <a href="shoppingcart.html">Show</a>' : 
  'articles in shopping  cart <span class="simpleCart_quantity"></span>- <span class="simpleCart_total"></span> <a href="shoppingcart.html">Show</a>');

如果你使用的字符串唯一的区别在于"article"结尾是否有"s",那么尝试使用以下方法:

return quantity + (quantity == 1 ? 'article' : 'articles') +
       ' in shopping cart <span class="simpleCart_quantity"></span>- <span class="simpleCart_total"></span> <a href="shoppingcart.html">Show</a>';

你在问题中添加的示例存在语法错误。请查看我的编辑。 - nnnnnn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接