意外的令牌错误:在书签中

unexpected token error: in bookmarklet

本文关键字:书签 错误 令牌 意外      更新时间:2023-09-26

这个想法是写一个简单的书签。如果问题可能是重复的,请指出我,因为我没有成功找到。

我正在尝试使用书签启用当前页面 jquery 并使用某些 jquery API。

未捕获的语法错误:意外令牌非法

上面是我使用以下示例书签得到的错误

javascript:(function(){
 var d=document.createElement('script');
 d.setAttribute('src', 'http://code.jquery.com/jquery-latest.js');
 document.head.appendChild(d);
 $('a').each(function(){
  alert( $(this).attr('src') );
 });
})()

如果我在控制台中逐行执行相同的代码,它可以工作。

提前致谢

若要使页面等到 jQuery 完全加载,请将加载处理程序添加到 script 元素。这在我的浏览器中有效:

javascript:(function(){
 var d=document.createElement('script');
 d.src = 'http://code.jquery.com/jquery-latest.js';
 d.onload = function(){ /* load handler here */
   $('a').each(function(){
     console.log( $(this).attr('href') );
   });
 };
 document.getElementsByTagName('head')[0].appendChild(d);
})()

我稍微更改了您的代码(将 src 属性直接作为属性添加到创建的 script 元素中,以更经典的方式检索 head 元素,使用 console.log 而不是 alert 并记录所有链接的 href 属性)。