[英]Cannot add class to next element of $(this)
I want to add class, next to checked input.我想在选中的输入旁边添加类。 So, class will be added to span, which is next to a checked input radio.
因此,类将被添加到 span,它位于选中的输入收音机旁边。
<label>
<input type="radio" name="option[228]" value="20" checked="checked">
<span data-toggle="tooltip" data-placement="top" title="" data-original-title="Purple (+₹20)">
<img src="http://countrylivings.com/image/cache/catalog/sample/q2-50x50.png" alt="Purple +₹20" width="36px" height="36px">
</span>
</label>
I have tried a no.我试过没有。 of ways to do so... But didn't work.
这样做的方法......但没有用。 like---
喜欢 - -
$(document).ready(function(){
if ($('label input').is(':checked')) {
$(this.element).next().addClass('hloo');
alert($(this.element).val());
};
});
But i get an alert of undefined when input is checked .但是当检查输入时我收到未定义的警报。 So,
所以,
if ($('label input').is(':checked')) {
is working fine to detect if checkbox is checked But可以正常检测复选框是否被选中但是
$(this) or $(this.element)
is not working.不管用。 Anyone know what is going wrong?
有谁知道出了什么问题?
There's three issues in your code.您的代码中存在三个问题。 Firstly
::checked
is not a valid jQuery selector, it's just :checked
.首先
::checked
不是有效的 jQuery 选择器,它只是:checked
。
Secondly, assuming this
is a reference to an Element object (as it is in the vast majority of cases in jQuery) then there is no element
property.其次,假设
this
是对 Element 对象的引用(在 jQuery 中的绝大多数情况下都是如此),则没有element
属性。 Just use $(this)
.只需使用
$(this)
。
Lastly, if
conditions run under the outer scope, so this
would refer to the document
in your example, not the input
.最后,
if
条件在外部范围内运行,那么this
将引用您示例中的document
,而不是input
。 It's for this reason val()
is undefined;正是因为这个原因
val()
是未定义的; you're looking at document.value
.您正在查看
document.value
。 To fix this, select the element directly before working with it:要解决此问题,请在使用该元素之前直接选择该元素:
$(document).ready(function() { var $checkedInput = $('label input:checked'); $checkedInput.next().addClass('hloo'); console.log($checkedInput.val()); });
.hloo { color: #C00; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <label> <input type="radio" name="option[228]" value="20" checked="checked"> <span data-toggle="tooltip" data-placement="top" title="" data-original-title="Purple (+₹20)"> <img src="http://countrylivings.com/image/cache/catalog/sample/q2-50x50.png" alt="Purple +₹20" width="36px" height="36px"> </span> </label>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.