gpt4 book ai didi

javascript - attr ('value' )返回未定义

转载 作者:行者123 更新时间:2023-11-28 05:40:12 24 4
gpt4 key购买 nike

我试图获取 5 星评级的值属性,但是当我将鼠标悬停在它上面时,我得到了未定义的结果。当我使用 attr('class') 而不是 attr('value') 时,它会起作用。我想知道是否有人可以帮助我。谢谢。

 <fieldset class="rating">
<input type="radio" id="star5" name="rating" value="5" /><label class = "full" for="star5" title="Awesome - 5 stars"></label>
<input type="radio" id="star4half" name="rating" value="4 and a half" /><label class="half" for="star4half" title="Pretty good - 4.5 stars"></label>
<input type="radio" id="star4" name="rating" value="4" /><label class = "full" for="star4" title="Pretty good - 4 stars"></label>
<input type="radio" id="star3half" name="rating" value="3 and a half" /><label class="half" for="star3half" title="Meh - 3.5 stars"></label>
<input type="radio" id="star3" name="rating" value="3" /><label class = "full" for="star3" title="Meh - 3 stars"></label>
<input type="radio" id="star2half" name="rating" value="2 and a half" /><label class="half" for="star2half" title="Kinda bad - 2.5 stars"></label>
<input type="radio" id="star2" name="rating" value="2" /><label class = "full" for="star2" title="Kinda bad - 2 stars"></label>
<input type="radio" id="star1half" name="rating" value="1 and a half" /><label class="half" for="star1half" title="Meh - 1.5 stars"></label>
<input type="radio" id="star1" name="rating" value="1" /><label class = "full" for="star1" title="Sucks big time - 1 star"></label>
<input type="radio" id="starhalf" name="rating" value="half" /><label class="half" for="starhalf" title="Sucks big time - 0.5 stars"></label>

</fieldset>

这是 JavaScript

 $(document).on('mouseover', '.rating', function(e) {
var c = $(e.target).attr('value')
alert(c);

});

最佳答案

更改事件监听器,它是当前警报字段集上任何鼠标悬停事件的事件监听器,如果您只对输入标记 div 感兴趣,那么您需要 . rating input 而不是 . rating

选项 1:

 $(document).on('mouseover', '.rating input', function(e) {
var c = $(e.target).attr('value')
console.log(c);
alert(c);
});

https://jsfiddle.net/uexycqxo/2/

选项 2:

另一个选项是使用 JQuery .is,这可以让您测试元素集的内容,并且可以将原始事件监听器保留在 . rating 标记上。

 $( ".rating" ).on('mouseover', function( event ) {  
var target = $( event.target );
if ( target.is( "input" ) ) {
var value = target.attr('value')
alert(value);
}
});

https://jsfiddle.net/uexycqxo/3/

希望有帮助。

关于javascript - attr ('value' )返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38978445/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com