javascript - 更改星星颜色 onClick - 为什么这不起作用?

标签 javascript jquery css

我有一个非常简单的星级评定系统。我遇到的问题是 onclick 事件,应该在单击时更改星星的颜色。

我创建了一个 jsFiddle对于我目前所拥有的。

HTML

<div class="rating">
<span id="five-stars" onclick="vote(5); return false; 
document.getElementById('five-stars').style.color = '#ff6266'" 
data-toggle="tooltip" data-placement="bottom" title="Rate 5 stars out of 5">
&#9734;</span><span id="fout-stars" onclick="vote(4); return false; 
document.getElementById('four-stars').style.color = '#ff6266'" 
data-toggle="tooltip" data-placement="bottom" title="Rate 4 stars out of 5">
&#9734;</span><span id="three-stars" onclick="vote(3); return false; 
document.getElementById('three-stars').style.color = '#ff6266'" 
data-toggle="tooltip" data-placement="bottom" title="Rate 3 stars out of 5">
&#9734;</span><span id="two-stars" onclick="vote(2); return false; 
document.getElementById('two-stars').style.color = '#ff6266'" 
data-toggle="tooltip" data-placement="bottom" title="Rate 2 stars out of 5">
&#9734;</span><span id="one-star" onclick="vote(1); return false; 
document.getElementById('one-star').style.color = '#ff6266'" 
data-toggle="tooltip" data-placement="bottom" title="Rate 1 star out of 5">
&#9734;</span>
</div>

CSS

.rating {
    color:#02dbdd;
    font: 700 26px/normal 'Montserrat', sans-serif;
    text-transform:uppercase;
    display:block;
    cursor:pointer;
    margin-right:100px;
}
.rating {
  unicode-bidi: bidi-override;
  direction: rtl;
}
.rating > span {
  display: inline-block;
  position: relative;
  width: 1.1em;
}
.rating > span:hover:before,
.rating > span:hover ~ span:before {
   content: "\2605";
   position: absolute;
}

不确定为什么它不会改变?

(RTL 是另外一个需要解决的问题……哈哈)

最佳答案

您有三个不同的问题会直接影响您的测试:

  1. 您已经配置了 JS Fiddle,以便 JS Pane 中的代码被包装在一个函数中并在加载时执行。这意味着您的函数不是全局函数,并且无法访问内部事件属性。更改 JS Fiddle 的配置或重写代码以使用 JS 而不是 HTML 绑定(bind)事件处理程序。
  2. 您没有配置 JS Fiddle 来加载 jQuery,因此当您尝试调用 $.post 时会出错,因为 $ 未声明。添加 jQuery。
  3. 在尝试设置颜色之前,您已将return false 放入函数中。函数自然会在到达该行之前返回。删除 return false

关于javascript - 更改星星颜色 onClick - 为什么这不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33596124/

相关文章:

javascript - 如何使用 Node 从 mySQL 初始化变量

jQuery UI datepicker - 我可以格式化已本地化的日期吗?

html - 如何用占位符居中标签?

html - Bootstrap : from Css to Config

影响 CSS 规则的 JavaScript/jQuery 函数

javascript - FB.login 不触发 HTML5 iOS 网络应用程序

javascript - 如何根据多个条件更改数组中某项的值?

javascript - Typescript 无法在克隆存储库上编译

javascript - 通过jquery显示php json编码数组的值时出现未定义错误

javascript - 当没有用户事件时自动注销