鼠标单击按钮时更改悬停颜色

时间:2019-05-05 15:37:03

标签: javascript jquery

我试图在鼠标单击按钮时更改悬停颜色,但是通过浏览器出现错误,请检查以下内容。

浏览器结果:

VM898 home.php:62 Uncaught TypeError: Cannot read property 'link-privacy-policy' of undefined
    at HTMLAnchorElement.<anonymous> (VM898 home.php:62)
    at HTMLAnchorElement.handle (jquery-3.4.0.js:5707)
    at HTMLAnchorElement.dispatch (jquery-3.4.0.js:5233)
    at HTMLAnchorElement.elemData.handle (jquery-3.4.0.js:5040)

jQuery代码

<script>
    let color_count = 0;
    let colors = [{
        "name": "blue",
        "btn-change-color": "#7f8ff4",
        "btn-start": "#7f8ff4",
        "link-privacy-policy": "#7f8ff4"
    },
        {
            "name": "orange",
            "btn-change-color": "#f8d745",
            "btn-start": "#f8d745",
            "link-privacy-policy": "#f8d745"
        }];
    let btnChangeColor = document.getElementsByClassName("btn-change-color");
    let btnStart = document.getElementsByClassName("btn-start");
    let linkPrivacyPolicy = document.getElementsByClassName("link-privacy-policy");
    $(".btn-change-color").click(function () {
        $(btnChangeColor).css("background", colors[color_count]["btn-change-color"]);
        $(btnStart).css("background", colors[color_count]["btn-start"]);
        $(linkPrivacyPolicy).hover(function () {
            $(this).css('color', colors[color_count]["link-privacy-policy"]);
            $(this).css('border-bottom', '1px solid ' + colors[color_count]["link-privacy-policy"]);
        })
        color_count++;
    });
</script>
  

注意:第62行从此行开始:
  $(this).css('color',colors [color_count] [“ link-privacy-policy”]);

2 个答案:

答案 0 :(得分:1)

破译错误消息有时会令人困惑:

List<JsonCurrent> collected = 
cars.parallelStream().map(car -> carService.createJson(car, calendarWeek, currentWeek, carPositionService.carPosition(car.getId())).collect(toList());     
carList.addAll(collected);

这实际上意味着以下代码...

 Cannot read property 'link-privacy-policy' of undefined

...由于 colors[color_count]["link-privacy-policy"] 的计算结果为colors[color_count]而引发错误-自然,该值没有属性undefined

@Robin Zigmond的评论(在我输入此答案时添加)可能解释了为什么您点击link-privacy-policy

答案 1 :(得分:0)

嘿,这里有一个带有2个对象的表colors,当用户单击color_count增量时,您应该添加一个条件来解决此问题:

    $(".btn-change-color").click(function () {
            $(btnChangeColor).css("background", colors[color_count]["btn-change-color"]);
            $(btnStart).css("background", colors[color_count]["btn-start"]);
            $(linkPrivacyPolicy).hover(function () {
                $(this).css('color', colors[color_count]["link-privacy-policy"]);
                $(this).css('border-bottom', '1px solid ' + colors[color_count]["link-privacy-policy"]);
            });
            color_count++;
            //You will add this condition
            if(color_count >= colors.length)
                 color_count = 0;

        });