首页 > 解决方案 > WCFM 每次添加产品时自动设置或附加类别

问题描述

它具有称为“峰值”的类别。每次添加新产品时,我都希望自动附加一个“峰值”类别,而无需手动选择它或将其视为我的默认值。

我怎样才能使用javascript实现。请帮忙。

这是我的 html 看起来像:

<span class="select2 select2-container select2-container--default select2-container--below" dir="ltr" style="width: 100%;">
<span class="selection"><span class="select2-selection select2-selection--multiple" role="combobox" aria-haspopup="true" aria-expanded="false" tabindex="-1">
<ul class="select2-selection__rendered">
<li class="select2-selection__choice" title="peak"><span class="select2-selection__choice__remove" role="presentation">×</span>peak</li>
<li class="select2-search select2-search--inline"><input class="select2-search__field" type="search" tabindex="0" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" role="textbox" aria-autocomplete="list" placeholder="" style="width: 3.75em;"></li>
</ul></span>
</span><span class="dropdown-wrapper" aria-hidden="true"></span></span>

标签: javascriptwoocommerce

解决方案


我对 WooCommerce 一无所知,因此我不知道您打算如何将您的 JavaScript 片段包含到更大的图片中。但是假设 WCFM 已经为您创建了一个 select2 结构,其中没有“峰值”类别,您可以触发addPeak()如下所示的函数。这会将您的 category-<li>插入到 select2 结构中。

在我的示例代码中,我通过单击按钮触发该函数并使用简单的 CSS 选择器 ('ul') 来查找父元素。这些东西需要在您的目标代码中进行调整(改进)。

document.querySelector('button').onclick=()=>addPeak('ul');

function addPeak(sel){
  let ul=document.querySelector(sel);
  if (ul) ul.innerHTML='<li class="select2-selection__choice" title="peak"><span class="select2-selection__choice__remove" role="presentation">×</span>peak</li>'+
ul.innerHTML;

}
<span class="select2 select2-container select2-container--default select2-container--below" dir="ltr" style="width: 100%;">
<span class="selection"><span class="select2-selection select2-selection--multiple" role="combobox" aria-haspopup="true" aria-expanded="false" tabindex="-1">
<ul class="select2-selection__rendered">
<li class="select2-selection__choice" title="other"><span class="select2-selection__choice__remove" role="presentation">×</span>other</li>
<li class="select2-search select2-search--inline"><input class="select2-search__field" type="search" tabindex="0" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" role="textbox" aria-autocomplete="list" placeholder="" style="width: 3.75em;"></li>
</ul></span>
</span><span class="dropdown-wrapper" aria-hidden="true"></span></span>
<button> test </button>


推荐阅读