未捕获的TypeError:无法读取未定义的属性"on"

Hol*_*oly -1 javascript jquery

在控制台中,我可以看到它releaseLink具有正在抓取的正确值(链接).但是当我尝试为它创建一个click事件时,在下一行,我在控制台中收到此错误:

Uncaught TypeError: Cannot read property 'on' of undefined

这是jQuery:

var releaseLink = $( "#release-link")[0];
var previousLink = $( "#prev-link" )[0];

  releaseLink.on('click', function(){
    console.log('hello. you clicked the release notes link');
  });
Run Code Online (Sandbox Code Playgroud)

这是与之关联的html.

<div id="release-notes">
    <h3><a id="release-link" href="#">Release Notes</a></h3>
    <div id="release-notes"></div>
</div>

<div id="previous-versions">
     <h3><a id="prev-link" href="#">Previous Versions</a></h3>
     <div id="version-notes"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

Ste*_*her 5

但是使用[0]你已经将jQuery对象剥离为DOM元素..on是一个jQuery方法,并没有在DOM对象上定义.

[0]无论如何都没有必要使用,因为您是通过ID选择的.除非您复制了非法HTML的元素ID,否则可以安全地假设您的jQuery选择器只返回一个对象.