<分区>
编辑问题以包含 desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem .这将有助于其他人回答问题。
关闭 6 年前。
标签 javascript jquery html css
<分区>
编辑问题以包含 desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem .这将有助于其他人回答问题。
关闭 6 年前。
我想让星星在我点击它时变色,但是因为我在单独的文件夹中同时拥有 Javascript 和 HTML 文件,我怎样才能将 javascript 中的功能恢复到 html 文件中?
HTML
<input type="hidden" name="rating" id="rating" />
<ul>
<li id="fav">★</li>
</ul>
Javascript
function addRating(obj) {
$('li').each(function(index) {
$(this).toggleClass('selected');
$('#rating').val((index+1));
if(index == $("li").index(obj)) {
return false;
}
});
}
$("#fav").click(function(){
addRating(obj);
});
CSS
li{float:left; margin-left:9px;display: inline-block;color: #F0F0F0;text-shadow: 0 0 1px #666666;font-size:30px;}
.highlight, .selected {color:#F4B30A;text-shadow: 0 0 1px #F48F0A;}
最佳答案
只需将 this
传递给 addRating
它保存所有者对象的上下文。
function addRating(obj) {
$('li').each(function(index) {
$(this).toggleClass('selected');
$('#rating').val((index + 1));
if (index == $("li").index(obj)) {
return false;
}
});
}
$("#fav").on('click',function() {
addRating(this);
});
li {
float: left;
margin-left: 9px;
display: inline-block;
color: #F0F0F0;
text-shadow: 0 0 1px #666666;
font-size: 30px;
}
.highlight,
.selected {
color: #F4B30A;
text-shadow: 0 0 1px #F48F0A;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" name="rating" id="rating" />
<ul>
<li id="fav">★</li>
</ul>
关于javascript - 点击最喜欢的明星,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43752265/