Strings
In Javascript you can use both single quotes ( ‘xxx’ ) and double quotes ( “xxx” ) in string expressions. If you want a string inside a string you can write it like this: s=’x=”hello”;’. Since you should always use single quotes (it makes it easier to distribute your bookmarklets), you should in stead write it like this: s=’x=’hello’;’. The backslash before the apostrophes means the apostrophe should be considered a character inside the string.
Literalised single quotes (that’s what they’re called when they have a backslash in front) are also practical when you have words or sentences that use apostrophes, like so: s=’Rock’n'roll isn’t dead’.
Finally, you can sometimes use the escape and unescape functions. unescape(%27) is a single quote. The browser will automatically render it as a single quote when the bookmarklet executes.
The function() Trick
Tired of using void to catch return values? If you put the statement (function(){…})() around your code it is encapsulated so you automatically catch all return values. The (function(){…}) part creates a nameless function. The () part runs it. This works in all browsers. Example:
javascript:
(function(){
…
x=3;
lnks=document.links;
document.links[0].href=’http://www.ibm.com/’;
…
})
()
Normally you would have to use void to catch the return values (see explanation on the rules page), but using the function() trick you don’t have to worry about that.
Script Inclusion
When you want to create bookmarklets with extensive logic it can be a good idea to create an external javascript file ( *.js), then include this file in the currently loaded page.
So far only Internet Explorer allows you to do this. Here’s the code:
var script=document.createElement(’script’);
script.src=’http://…mysite…/…myscript.js’;
document.getElementsByTagName(’head’)[0].appendChild(script);
…
/* Call functions found in myscript.js here */
Alternatively, have your bookmarklet open a new window. In the document of this new window you write a copy of the current document, with the exception that you slip in your script reference, using the ‘);
var win=open();
with(win.document){
open();
write(src);
close();
}
…
/* Manipulate win using myscript.js functions */
以上技巧来自:
http://www.subsimple.com/bookmarklets/tips.asp
更多技巧:
http://www.subsimple.com/bookmarklets/links.asp#Articles
Leave a reply