Javascript 可用作书签,但不能用作 onclick 链接

Javascript 可用作书签,但不能用作 onclick 链接

问题描述:

我使用以下代码允许用户向浏览器添加书签,这非常有效,但如果我尝试从页面上的链接实际触发代码,则不会.

I use the following code to allow users to add a bookmarklet to browsers, which works perfectly, but if I try actually firing the code from a link on a page it does not.

我需要从代码中添加/减去一些不同的东西.

Is there something different I need to add/subtract from the code.

这是我使用的:

javascript:(function(d){
var%20modal=document.createElement('iframe');
modal.setAttribute('src','http://url.com/bm.html?
url='+encodeURIComponent(window.location.href)+'&page_title='+document.title);
modal.setAttribute('scrolling','no');
modal.setAttribute('name','my_modal');
modal.className='modal';
document.body.appendChild(modal);
var%20c=document.createElement('link');
c.type='text/css';
c.rel='stylesheet';
c.href='//iframe.css';
document.body.appendChild(c);}(document));

我尝试了以下但不起作用:

I tried the following but doesn't work:

<a href="#" onclick="javascript:(function(d){var%20modal=document.createElement('iframe');modal.setAttribute('src','http://url.com/bm.html?url='+encodeURIComponent(window.location.href)+'&page_title='+document.title);modal.setAttribute('scrolling','no');modal.setAttribute('name','my_modal');modal.className='modal';document.body.appendChild(modal);var%20c=document.createElement('link');c.type='text/css';c.rel='stylesheet';c.href='//iframe.css';document.body.appendChild(c);}(document));">test</a>

您必须:

  • 空格
  • 替换%20
  • 删除 javascript:

你也可以使用这个函数调用技巧 !function( ...

You could also use this function invocation trick !function( ...

试试这个:

<a href="#" onclick="!function(d){var modal=document.createElement('iframe');modal.setAttribute('src','http://url.com/bm.html?url='+encodeURIComponent(window.location.href)+'&page_title='+document.title);modal.setAttribute('scrolling','no');modal.setAttribute('name','my_modal');modal.className='modal';document.body.appendChild(modal);var c=document.createElement('link');c.type='text/css';c.rel='stylesheet';c.href='//iframe.css';document.body.appendChild(c);}(document)">test</a>