将 HTML 添加到 Javascript IF 函数

Adding HTML to Javascript IF function

本文关键字:IF 函数 Javascript HTML 添加      更新时间:2023-09-26

我正在尝试编辑脚本,以便我可以使用 HTML 格式化输出,但不确定如何正确格式化它。目前脚本如下,但我想实现的是下面的第二个脚本。我知道第二个脚本没有意义,但我只是想展示我基本上想要实现的目标,但不确定如何实现它。如果有人能帮忙,我将不胜感激。

原脚本:

var selectCallback = function(variant, selector) {
timber.productPage({
  money_format: "{{ shop.money_format }}",
  variant: variant,
  selector: selector
});
if (variant) {
    if (variant.inventory_management == "shopify" && variant.inventory_policy != "continue") {
    if (variant.inventory_quantity > 0) {
    jQuery('#variant-inventory').text('We have ' + variant.inventory_quantity + ' in stock.');
    } else {
    jQuery('#variant-inventory').text("This product is sold out");
    }
    } else {
    jQuery('#variant-inventory').text("In stock - order now");
    }
    } else {
    jQuery('#variant-inventory').text("");
    }
};

我想要实现的目标:

var selectCallback = function(variant, selector) {
timber.productPage({
  money_format: "{{ shop.money_format }}",
  variant: variant,
  selector: selector
});
if (variant) {
    if (variant.inventory_management == "shopify" && variant.inventory_policy != "continue") {
    if (variant.inventory_quantity > 0) {
    jQuery('#variant-inventory').text('<div class="stock">We have ' + variant.inventory_quantity + ' in stock.</div>');
    } else {
    jQuery('#variant-inventory').text("<div class="sold-out">This product is sold out</div> - <a href="link">contact us</a>");
    }
    } else {
    jQuery('#variant-inventory').text("<div class="in-stock">In stock</div> - order now");
    }
    } else {
    jQuery('#variant-inventory').text("");
    }
};

与其使用.text()不如使用.html()

jQuery('#variant-inventory').html('<div class="stock">We have ' + variant.inventory_quantity + ' in stock.</div>');

.text()只是一种更简单的Element.textContent||Element.innerText||...etc =方法,它用(nodeType 3(字符串更改完整的内容,"打印">标签字符字面上> <。
另一方面,.html()是一个jQuery方法,它使用JS的Element.innerHTML实际上插入类似HTML的字符串,使它们成为实际的DOM节点。


注意报价!!这是不正确的:

"<div class="sold-out">This product is sold out</div> - <a href="link">contact us</a>"

应该是:

'<div class="sold-out">This product is sold out</div> - <a href="link">contact us</a>'

就像你在上面做了几行...


每日提示

照顾好你的手指!不要jQuery到处写,而是将其包装成一个速记 DOM ready,可以安全地封装$别名:

jQuery(function( $ ) {                          // DOM ready and $ alias secured in scope
  // Your DOM ready code here.
  // Now you're free to use the $ alias and save some bites and finger nails
  $('#variant-inventory').html("YEY!!");
});
使用 jQuery.html((

而不是 jQuery.text((