开发者

onclick generates a fault

I have a web page with some links (there is no id assigned to these links). I want to add onclick feature to these links.开发者_运维技巧 by looking at the source code of that web page I realized that I can add onclick to the links using the following code:

doc = doc.replace(/&sa=N\"/g, "&sa=N\" onClick=\"alertsomething();return false;\"");

function alertsomething(){
alert('hello');
}

but when the web page is loaded and I click on these links the alertsomething function doesn't work. it generates the following page:

Object not found!

The requested URL was not found on this server. The link on the referring page seems to be wrong or outdated. Please inform the author of that page about the error.

If you think this is a server error, please contact the webmaster.

Error 404 localhost 12/05/2011 10:00:29 AM Apache/2.2.17 (Win32) mod_ssl/2.2.17 OpenSSL/0.9.8o PHP/5.3.4 mod_perl/2.0.4 Perl/v5.10.1

I checked the following code and it works properly

doc = doc.replace(/&sa=N\"/g, "&sa=N\" onClick=\"alert("hello");return false;\"");

I am using IE7.


Do not mess with the body.innerHTML unless you know exactly what you are doing. It will delete listeners that are added as DOM properties, also parsing HTML with a regular expression will certainly fail in any non-trivial page.

There is a document.links collection that is every link in the page, iterate over that and add your listener to each link. Or add a single click listener to the body and wait for clicks - if they come from a link, do your stuff.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜