【问题标题】:jQuery addClass and removeClass onchange issuejQuery addClass 和 removeClass onchange 问题
【发布时间】:2011-10-19 09:50:59
【问题描述】:

我试图让 jQuery 的 addClass 和 removeClass 在表单选择环境中工作,但收效甚微。

我想修改父 div 的类,并试图在函数中传递 ID,但我所有的尝试都是徒劳的。任何指导和帮助将不胜感激。

<div id="MaxAge" class="SearchFormStyle">
                <select name="maxage" onchange="addClass(MaxAge);">
                    <option value="0">Age</option>
                    <option value="1" >1 Year Old</option>
                    <option value="2" >2 Years Old</option>
                </select>
                    <span class="ThisValue">
                        <a href="#" onclick="RemoveClass(MaxAge)">VALUE ENTERED HERE</a>
                    </span>
                </div>

<script>
    function addClass (id) { 
        div = "#" + id; 
        $(div).addClass("InputSet"); 
    }
    function RemoveClass (id) { 
        div = "#" + id; 
        $(div).removeClass("InputSet"); 
    }
</script>

【问题讨论】:

  • 不太明白,到底想要什么效果?
  • 示例效果:autotrader.co.uk 在汽车搜索中,选择最高价格以查看效果。

标签: jquery css onchange addclass removeclass


【解决方案1】:

addClass(MaxAge) 会将变量的值 MaxAge 传递给addClass,而不是字符串'MaxAge'

此外,您确实应该使用 jQuery 来绑定事件处理程序而不是内联事件处理程序:

$("select[name='maxage']").change(function() {
    addClass('MaxAge');
});

$('.ThisValue a').click(function(event) {
    RemoveClass('MaxAge');
    event.preventDefault();
});

要了解有关事件处理程序的更多信息,我建议阅读articles at quirksmode.org


还有其他问题,例如addClassRemoveClass 中的div 变量是全局。声明变量时不要忘记var。函数的命名也不一致addRemove

MDN JavaScript Guide 非常适合学习 JavaScript 基础知识。

【讨论】:

    【解决方案2】:

    您几乎以正确的方式进行操作。这就是我要做的(为你准备一些 cmets)

    // onchange event of the selectbox with id = maxage
    $("#maxage").change(function() {
        $("#MaxAge").addClass("InputSet");
    });
    
    // the click event for the a element within span with class ThisValue
    $("span.ThisValue a").click(function(e) {
        // prevent doing default behaviour like going to another location...
        e.preventDefault();
        $("#MaxAge").removeClass("InputSet");
    });
    

    【讨论】:

    • 我的表单中有大约 10 个选择,因此拥有一个可以处理所有选择的函数而不是每个元素 ID 的函数会更容易。希望这是有道理的?
    【解决方案3】:

    你永远不会实例化 div 变量。

    试试这个:

    var div = "#" + id; 
    

    【讨论】:

    • 谢谢,但这没有效果
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-28
    • 1970-01-01
    • 2013-02-18
    • 1970-01-01
    相关资源
    最近更新 更多