Javascript首次亮相 - 从Chrome控制台到书签 [英] Javascript debut - from Chrome console to a bookmarklet
问题描述
我是JS的新手,我试图为一个网站写一个简单的小书签,其div类的collapseable设置为display:none;我想通过一次单击设置所有元素类可折叠显示:块。
浏览这个网站,我设法把下面的代码,当我粘贴在谷歌浏览器的JS控制台工作正常:它返回值块,但对网站的影响是我寻求的。但是,当我创建一个带有javascript:mycode ...的书签,它只会带来一个空白页的文本块。
I am new to JS and am trying to write a simple bookmarklet for a website that has divs with class "collapseable" set to display: none; I want by one click to set all elements with class "collapseable" to display: block. Browsing this website, I managed to put together the following code, which works fine when I paste it in Google Chrome's JS console: it returns the value "block" but the effect on the website is the one I seek. However, when I create a bookmarklet with URL javascript:mycode... , it only brings up a blank page with the text "block".
这里是我的代码,我非常感谢,如果有人可以告诉我我做错了:
Here is my code, I would very much appreciate if somebody could tell me what I'm doing wrong:
javascript:function getElementsByClassName(classname, node) {
if(!node) node = document.getElementsByTagName("body")[0];
var a = [];
var re = new RegExp('\\b' + classname + '\\b');
var els = node.getElementsByTagName("*");
for(var i=0,j=els.length; i<j; i++)
if(re.test(els[i].className))a.push(els[i]);
return a;};
var elems = getElementsByClassName('collapseable');
for (var i=0;i<elems.length;i+=1){
elems[i].style.display = 'block';}
推荐答案
当我尝试自己制作一个bookmarklet时,我有同样的问题。我的解决方案是使用 void(function({/ * your code * /})()
。
When I tried making a bookmarklet myself, I had the same problem. My solution was to use void (function({ /* your code */ })()
.
javascript:void(function(){
var getElsByCN = document.getElementsByClassName ||
function(classname, node) {
if(!node) node = document.body;
var a = [],
re = new RegExp('\\b' + classname + '\\b'),
els = node.getElementsByTagName("*");
for (var i = 0, j = els.length; i < j; i++)
if (re.test(els[i].className))
a.push(els[i]);
return a;
};
var elems = getElsByCN('collapseable');
for (var i = 0; i < elems.length; i++)
elems[i].style.display = 'block';
)();
这是因为因为使用 void $>而返回
undefined
c $ c>。当你的脚本在页面上写 block
时,很可能是因为这是函数设置/访问的最后一个值。
This works because it returns an undefined
value due to the use of void
. When your script wrote block
on the page, it was likely because that was the last value set/accessed by the funtion.
这篇关于Javascript首次亮相 - 从Chrome控制台到书签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!