javascript - Bookmarklet unexpectedly opens new page on click -
so made bookmarklet collapse every row in table, except first one, make first row toggle/show rest of table:
javascript:(function(){ function open(tableid){ console.log('open'); (j=1;j<table[tableid].rows.length;j++){ if(table[tableid].rows[j].style.display == 'none' ){ table[tableid].rows[j].style.display = ''; } else if(table[tableid].rows[j].style.display == ''){ table[tableid].rows[j].style.display = 'none'; } } } var table = document.getelementsbytagname("table"); (i=0;i<table.length;i++){ (j=0;j<table[i].rows.length;j++){ if( j != 0){ table[i].rows[j].style.display = 'none'; } if( j == 0){ table[i].rows[j].onclick = new function("open("+i+")"); } } } })(); i run without javascript:(function(){}() in firebug's console, , works fine. when use bookmarklet, every time click on first row show table, opens new page '0' (i.e. website.com/0 )
the function constructor creates global function, not lexically within function. therefore, doesn't have access local function called open, uses window's open method.
from tests, code should referencing global open method whether run bookmarklet or page itself.
look @ example:
(function(){ function giveme5(x) { return 5;} var func = new function("return giveme5()"); // should output 5, error, giveme5 not defined console.log( func() ); })() here's possible solution problem
(function(){ // binds argument method, better, serves our // purpose here function bindarg(fun, arg) { return function() { fun.call(this, arg); } } function toggletable(table) { var rows = table.rows; (var j=1; j<rows.length; j++){ if(rows[j].style.display == 'none' ){ rows[j].style.display = ''; } else if(rows[j].style.display == ''){ rows[j].style.display = 'none'; } } } var tablelist = document.getelementsbytagname("table"); ( var i=0; i<tablelist.length; i++){ var table = tablelist[i]; ( var j=0; j < table.rows.length;j++){ if( j != 0){ table.rows[j].style.display = 'none'; } else { table.rows[j].onclick = bindarg(toggletable, table); } } } })();
Comments
Post a Comment