单击特定按钮时,如何更改跨度的颜色

时间:2019-01-15 13:42:58

标签: javascript jquery html css

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<span class="vote-stars number-0" method="get">
    <button id="1" class="submitUserVote"><span class="fa fa-star"></span></button>
    <button id="2" class="submitUserVote"><span class="fa fa-star"></span></button>
</span>

<br><br><br>

<span class="vote-stars number-1" method="get">
    <button id="1" class="submitUserVote"><span class="fa fa-star"></span></button>
    <button id="2" class="submitUserVote"><span class="fa fa-star"></span></button>
</span>

当用户单击按钮时,我希望运行Jquery代码并更改按钮内特定跨度的颜色。

2 个答案:

答案 0 :(得分:2)

<button onclick="$(this).children('span').css('color', 'red')">

我认为“ onclick”足以找到子“ span”并使用“ .css”功能更改颜色。

答案 1 :(得分:0)

您对问题的评论中显示的代码可以正常工作。您需要确保将jQuery逻辑放置在document.ready事件处理程序中,并且已将创建的click事件附加到button元素上。另请注意,应避免使用内联css()调用,而应在元素中添加预定义的CSS类。试试这个:

$(function() {
  $('button').click(function() {
    $(this).find('span').addClass('foo');
  });
});
.foo {
  color: orange;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<span class="vote-stars number-0" method="get">
    <button id="1" class="submitUserVote"><span class="fa fa-star"></span></button>
<button id="2" class="submitUserVote"><span class="fa fa-star"></span></button>
</span>

<br><br><br>

<span class="vote-stars number-1" method="get">
    <button id="1" class="submitUserVote"><span class="fa fa-star"></span></button>
<button id="2" class="submitUserVote"><span class="fa fa-star"></span></button>
</span>