【问题标题】:Performing an action when clicking on a select option, but with unknown id单击选择选项时执行操作,但 ID 未知
【发布时间】:2014-02-27 04:47:25
【问题描述】:

我在这里遇到了 jquery、wordpress 和 twig 的大问题。

我的目标是在用户从选择中选择一个选项时显示预定义的选择。问题是我不知道如何检查他选择了哪个选项,因为我无法使用 wp_dropdown_categories 获取选项值。更难让它成为 Twig 引擎,它不允许我使用每个 php 函数。

我已经用这段代码解决了这个问题:

jQuery("#property_contract_haupt option:eq( {{ foo-1 }} )").click(function () {
                            {% for i in 0..10 %}
                            jQuery('#property_contract_no{{ i }}').hide();
                            jQuery('#input{{ i }}').hide();
                            {% endfor %}
                            jQuery('#property_contract_no{{ foo }}').show();

                            <!-- show an input if there is one for the number of foo -->
                            jQuery('#input{{ foo }}').show();
                    });

但不幸的是,该解决方案在 Chrome 或 Safari 中不起作用,因为单击选项似乎不合法。我已经阅读了很多关于该问题的线程并发现我需要使用 on change 事件,但是我无法识别所选选项,因为我无法获得选项的值。

如果您能帮我找到解决该问题的方法,我会很好。

【问题讨论】:

    标签: php jquery wordpress twig


    【解决方案1】:

    使用下面的代码:

    jQuery("#property_contract_haupt").on("change", function(){
        if(jQuery(this).value === "the desired option value attribute"){
            // do my desired action
        }
    });
    

    【讨论】:

    • 感谢您的回答,但内容不是静态的,我使用 wp_dropdown_categories 读取类别,这使得无法检查选项的值。
    • 我看到在你的代码中你依赖于选项的索引,因为你可以使用: $(this).prop('selectedIndex'): 在更改事件中而不是 $( this).value()
    • 谢谢你,这对我有帮助!我很高兴我解决了这个问题,谢谢你
    猜你喜欢
    • 2015-07-13
    • 2012-12-06
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    • 2021-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多