javascript - Javascript 函数内的 CSS 出现在下拉菜单中
问题描述
我的 Javascript 代码出现在下拉菜单中(示例 URL 在这篇文章的底部)。我认为浏览器会忽略有效的 HTML,但在这个例子中似乎没有发生。
一些上下文:我有一个 Wordpress 网站并添加了 Javascript 代码,该代码在下拉菜单上的项目名称旁边添加价格变量。然后我尝试将一些 CSS 应用于 Javascript 输出(红色、向右浮动、填充),以便在项目名称旁边很容易看到变化价格。
这是代码:
function display_price_in_variation_option_name( $term ) {
$product = wc_get_product();
$id = $product->get_id();
if ( empty( $term ) || empty( $id ) ) {
return $term;
}
if ( $product->is_type( 'variable' ) ) {
$product_variations = $product->get_available_variations();
} else {
return $term;
}
foreach($product_variations as $variation){
if(count($variation['attributes']) > 1){
return $term;
}
foreach($variation['attributes'] as $key => $slug){
if("attribute_" == mb_substr( $key, 0, 10 )){
$taxonomy = mb_substr( $key, 10 ) ;
$attribute = get_term_by('slug', $slug, $taxonomy);
if($attribute->name == $term){
$term .= " <span style=\"color: red; float: right; padding: 0% 7% 0% 0%;\"> " . wp_kses( wc_price($variation['display_price']), array()) . " </span> ";
}
}
}
}
return $term;
}
add_filter( 'woocommerce_variation_option_name', 'display_price_in_variation_option_name' );
但随后我的内联 CSS 代码出现在下拉菜单中。
这是正在发生的事情的示例 URL:
http://66.228.41.220/product/v-neck-t-shirt/
在该页面上,单击该下拉菜单并注意<span>
出现 HTML 代码。
于是我尝试将 Javascript 函数放入一个元素中,这样我就可以在我的 style.css 中访问它。使用这种方法:
https://developer.mozilla.org/en-US/docs/Web/API/ElementCSSInlineStyle/style
但我似乎无法成功。我在这里想念什么?
解决方案
您看到的 html 代码是由于 woocommerce 应用于esc_html()
您的输出。它将之类的东西转换<
为<
.
在元素的规范中,option
它声明唯一允许的内容是:
文本,可能带有转义字符(如 é)。
所以你不能在一个option
元素中有任何标签。你可以试试这个 javascript 例如:
$('#pa_color option').each(function(i, optionEl){
var optionText = $(optionEl).text();
var startIndex = optionText.indexOf('$');
if(startIndex !== -1){
var priceText = optionText.substr(startIndex);
var restOfText = optionText.substring(0,startIndex);
var output = restOfText + '<span style="color: #565656; float: right; padding: 0% 7% 0% 0%;">' + priceText + '</span>';
$(optionEl).html(output);
}
});
正如您在开发人员控制台中看到的那样,它可以正常工作,但不会显示在页面上。浏览器只是忽略标签...
<select>
<option><span style="color:red;">first and only option</span></option>
</select>
如果你真的需要这个功能,你应该select
只使用 s 编写你自己的元素div
,或者你可以尝试找到一个像这些一样为你做的插件。
推荐阅读
- typescript - 使用 AWS Lambda + 反射元数据包的无服务器
- python - Python 倒计时,但在年、月、周、日、小时、分钟、秒
- r - 多年数据集中一年内的不同季节
- java - 使用 Java Netbeans 和 MySQL 存储自动生成的随机数
- android - 无法在 Android 中隐藏折叠的工具栏视图
- angular - 如何将 i18n 数据作为参数传递给组件
- python - 当我点击一个反应时,我如何分配一个角色?它对我不起作用?
- java - 如何在 Kotlin 中制作静态方法
- dynamic-programming - 如何将具有给定流行度的 n 个元素分配到 k 个通道中(动态规划)
- php - 单击链接/按钮PHP时如何执行sql查询