将 HTML 添加到 Javascript IF 函数
Adding HTML to Javascript IF function
我正在尝试编辑脚本,以便我可以使用 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((
相关文章:
- 将 HTML 添加到 Javascript IF 函数
- 这个基于iFrame选择器的if函数有什么问题
- HTML DOM 使用 AngularJS ng-if 函数
- 在 ng-if 函数上添加删除 HTML 标记链接
- 如果选中复选框,则执行 if 函数 角度.js.
- 在IF函数中使用REGEX
- angular for Each不使用ng if函数
- 每个循环查找if函数是否存在
- JavaScript弹出窗口显示在PHP IF函数没有onClick
- 内联PHP停止使用if函数和javascript
- 内部的HTML不以if函数为中心
- Javascript变量和基于HTML表单的If函数
- Angular js: "this"内部ng-if函数
- 在Google App Script中的IF函数中的IF函数
- javascript中的If函数没有返回任何结果
- if函数返回相同的输出
- 关于(if和esle-if函数)的进展
- Javascript和jquery if函数不工作
- 如何在按下按钮时执行 if 函数 (JavaScript)
- IF 函数中的 JavaScript 通配符