首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Javascript函数中的CSS出现在下拉菜单中。

Javascript函数中的CSS出现在下拉菜单中。
EN

Stack Overflow用户
提问于 2021-04-25 18:49:52
回答 1查看 55关注 0票数 0

我的Javascript代码出现在下拉菜单中(示例URL位于这篇文章的底部)。我以为浏览器会忽略有效的HTML,但在本例中似乎没有发生这种情况。

一些上下文:我有一个Wordpress网站并添加了Javascript代码,它在下拉菜单上的项目名称旁边添加价格变量。然后,我尝试将一些CSS应用于Javascript输出(颜色为红色、向右浮动、填充),以便在项目名称旁边很容易看到变化价格。

下面是代码:

代码语言: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>代码的出现。

因此,我尝试将Javascript函数放入元素中,以便在我的style.css中访问它。使用这种方法:

https://developer.mozilla.org/en-US/docs/Web/API/ElementCSSInlineStyle/style

但我似乎做不到成功。我在这里错过了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-26 01:20:41

您所看到的html代码是由于woocommerce将esc_html()应用于您的输出。它将像<这样的东西转换为&lt;

规格option元素中,它声明唯一允许的内容是:

文本,可能带有转义字符(如é)。

因此,您不能在option元素中有任何标记。例如,您可以尝试这个javascript:

代码语言: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);
    }
});

它可以像您在开发人员控制台中看到的那样工作,但是它不会显示在页面上。浏览器只是忽略标签..。

代码语言:javascript
复制
<select>
<option><span style="color:red;">first and only option</span></option>
</select>

如果您真的需要这个功能,您应该只使用select s编写自己的div元素,或者您可以尝试找到一个像这些这样的插件。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67257107

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档