1

我正在学习 codecademy.com 课程,该课程教我如何使用 jQuery 构建条形图。最后一组指令是向 $bar 添加一个点击事件以显示它的值。它解释了

匿名函数是这样的:function(arg) { code }. 在这种情况下, .click 处理程序将单击事件 e 作为其参数,因此您的实现应该function(e) { alert code }.click().

这是我应该修改的功能

// Exercise 5
function addBarClickEvent($bar,value) {
    // add a click event to the bar that 
    // pops up an alert with the bars value
    $bar.click(
        // your code goes here!

        }
    );
}

我尝试了下面显示的两种解决方案,但都没有奏效。不幸的是,该课程没有提供解决方案。任何人都可以帮忙。

// Exercise 5
    function addBarClickEvent($bar,value) {
        // add a click event to the bar that 
        // pops up an alert with the bars value
        $bar.click(
            // your code goes here!
              alert($bar.value)       //my attempt
              alert(e.value)          //my second attempt
            }
        );
    }

我收到此错误消息

确保将 .click 的参数定义为显示警报的匿名函数。

4

2 回答 2

2

假设您要显示的值是绑定时传递的值

function addBarClickEvent($bar,value) {
    // add a click event to the bar that 
    // pops up an alert with the bars value
    $bar.click(function(){
       alert(value);
    });
}

如果不 -

$bar.click(function(){
   // get value somehow
  //$(this).data('some-value');
});
于 2012-09-05T18:00:54.830 回答
0

该问题确切地告诉您该怎么做:“您的实现应该在 .click() 中包含 function(e) { alert code }”

只需写下它所说的:$bar.click(function(e) { alert(this.value); }

根据值的实际位置调整this.value- 我不知道也无法猜测;)

于 2012-09-05T18:11:02.687 回答