首页 > 解决方案 > 选择下拉菜单时如何更改标题文本

问题描述

On my WordPress site I am using jQuery to update the text inside a H2 header when options inside a drop down menu are selected.

下面的代码在这里完美运行,但我无法让它在我的实时站点上运行。

这是我正在使用的工作代码:

jQuery(document).ready(function() {
  jQuery("#wpfs-plan--NjUyMTB").change(function() {
    var selectedValue = this.value;
    if (selectedValue == 'SEO_500_word_articles') {
      jQuery('#price_value').text('299');
    } else if (selectedValue == 'SEO_1000_word_articles') {
      jQuery('#price_value').text('598');
    }
  });
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>

<h1 style="margin-bottom: 25px;">The price is: <span id="price_value">299</span></h1>

<select id="wpfs-plan--NjUyMTB" style="width: 200px;">
  <option value="SEO_500_word_articles">SEO 500 words $299</option>
  <option value="SEO_1000_word_articles">SEO 1000 words $598</option>
</select>

注意:我无法更改网站上的 HTML,因为它通过插件加载,我只能与 HTML 交互的 JavaScript。

标签: javascriptjquery

解决方案


如果选择标记的值以编程方式更改,则不会触发“更改”事件。

您必须使用包装自定义选择的小部件。经过一番挖掘,我发现自定义选择是在 wpfs.js 文件的第 1598 行创建的。

因此,如果您执行以下操作:

jQuery(document).ready(() => {
  jQuery('#wpfs-plan--NjUyMTB').wpfsSelectmenu({
    change() {
      const selectedValue = this.value;
      if (selectedValue === 'SEO_500_word_articles') {
        jQuery('#price_value').text('299');
      } else if (selectedValue === 'SEO_1000_word_articles') {
        jQuery('#price_value').text('598');
      }
    },
  });
});

它会将函数包装到小部件中,并且会被正确调用。


推荐阅读