首页 > 解决方案 > 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 .= "&nbsp;&nbsp; <span style=\"color: red; float: right; padding: 0% 7% 0% 0%;\"> &nbsp;&nbsp;" . wp_kses( wc_price($variation['display_price']), array()) . "&nbsp; </span> &nbsp;";
                }
            }
        }
    }
    
    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

但我似乎无法成功。我在这里想念什么?

标签: javascriptcsswordpressdomdropdown

解决方案


您看到的 html 代码是由于 woocommerce 应用于esc_html()您的输出。它将之类的东西转换<&lt;.

在元素的规范中,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,或者你可以尝试找到一个像这些一样为你做的插件。


推荐阅读