JQuery:addClass 不适用于具有多个类的元素。为什么?我很困惑!
这非常令人沮丧。这是为表单编写的一些代码的一部分。与验证错误关联的输入元素应显示红色边框。它适用于 .css 方法,但如果有人能告诉我为什么 .addClass 方法不起作用,我将不胜感激。
<style type="text/css">
.field_error{color:red;}
.red_border{border:1px solid red;}
</style>
<script>
$(document).ready(function(){
$('.field_error').siblings().addClass('red_border');
});
</script>
...
<label class="description" for="element_1">Email Address </label>
<div>
<input id="element_1" name="email" class="element text medium" type="text"/>
{% if form.email.errors %}
<div class="field_error">{{form.email.errors}}</div>
{% endif %}
</div>
..etc..
如果只为“element_1”分配一个类,它就可以正常工作。
我也可以这样做:
$('.field_error').siblings().css("border", "1px solid red");
但是,我计划向我要添加的类添加很多内容。 有没有办法让addClass方法起作用?
谢谢!!
马特
重要编辑
我忘记在我的代码中添加多个类。难怪有些人会感到困惑。请再次检查代码。
<input id="element_1" name="email" class="element text medium" type="text"/>
已解决
问题是我已经定义了文本输入元素边框的 css 文件。现在修好了。感谢所有与我同在的大脑。
This is very frustrating. This is part of some code written for a form. The input element that is associated with a validation error should display a red border. It works with the .css method, but I'd be grateful if someone could show me why the .addClass method isn't working.
<style type="text/css">
.field_error{color:red;}
.red_border{border:1px solid red;}
</style>
<script>
$(document).ready(function(){
$('.field_error').siblings().addClass('red_border');
});
</script>
...
<label class="description" for="element_1">Email Address </label>
<div>
<input id="element_1" name="email" class="element text medium" type="text"/>
{% if form.email.errors %}
<div class="field_error">{{form.email.errors}}</div>
{% endif %}
</div>
..etc..
If assign "element_1" only one class, it works just fine.
I can also do this instead:
$('.field_error').siblings().css("border", "1px solid red");
However, I plan on adding a lot of content to the class I will add. Is there a way to get the addClass method to work?
Thanks!!
Matt
IMPORTANT EDIT
I forgot to add in the multiple classes on my code. No wonder some people are confused. Please review code again.
<input id="element_1" name="email" class="element text medium" type="text"/>
Solved
The problem was that I had css file that defined the borders of the text input element already. Fixed now. Thanks to all who brain stored with me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对我有用: http://jsfiddle.net/JAAulde/KPckC/1/ (< em>已更新您的多类更正)
不过,您的代码中确实有一个拼写错误:
应该是
也许您的实时站点中存在该错误?
Works for me: http://jsfiddle.net/JAAulde/KPckC/1/ (updated with your multiple class correction)
You do have a typo in your code, though:
should be
Maybe that exists in your live site?