jQuery addClass 和 removeClass onchange 问题
我试图让 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>
I'm trying to get jQuery's addClass and removeClass to work in a form select environment with little success.
I want to modify the parent div's class and was trying to pass the ID in the function but all my attempts have been futile. Any direction and assistance would be much appreciated.
<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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
addClass(MaxAge)
会将变量的值MaxAge
传递给addClass
,而不是字符串'最大年龄'
。此外,您确实应该使用 jQuery 来绑定事件处理程序而不是内联事件处理程序:
要了解有关事件处理程序的更多信息,我建议阅读 quirksmode.org 上的文章。
还有其他问题,例如
addClass
和RemoveClass
中的div
变量是全局。声明变量时不要忘记var
。此外,函数的命名与add
和Remove
不一致。MDN JavaScript 指南非常适合学习 JavaScript 基础知识。
addClass(MaxAge)
will pass the value of the variableMaxAge
toaddClass
, not the string'MaxAge'
.Besides, you really should use jQuery to bind event handlers instead of inline event handlers:
To learn more about event handlers, I recommend to read the articles at quirksmode.org.
There are also other problems, like the
div
variable inaddClass
andRemoveClass
being global. Don't forgetvar
when you are declaring variables. Also the naming of the function is inconsistentadd
vsRemove
.The MDN JavaScript Guide is very good for learning the JavaScript basics.
你几乎正在以正确的方式做这件事。这就是我要做的(给你一些评论)
you're almost doing it the right way. Here's what I would do (with some comments for you)
您永远不会实例化 div 变量。
试试这个:
You're never instantiating the div variable.
Try this: