我使用一个网页,我想替换 onclick
s,一堆链接,修改为 src
<img>
的链接每个链接包含。
例如,Greasemonkey 脚本应更改此内容:
<p class="listphotos">
<a onclick="alert('I'm a really annoying function! X'); return false;" href="#">
<img alt="photo" src="http://.../min/x.jpg">
</a>
<a onclick="alert('I'm a really annoying function! Y'); return false;" href="#">
<img alt="photo" src="http://.../min/y.jpg">
</a>
</p>
对此:
<p class="listphotos">
<a onclick="http://.../max/x.jpg" href="http://.../max/x.jpg">
<img alt="photo" src="http://.../min/x.jpg">
</a>
<a onclick="http://.../max/y.jpg" href="http://.../max/y.jpg">
<img alt="photo" src="http://.../min/y.jpg">
</a>
</p>
我已经尝试过(另请参阅 this jsFiddle ):
var link = $("p.listphotos a img").prop("src").replace("min", "max");
$("p.listphotos a").prop("onclick", link);
$("p.listphotos a").prop("href", link);
但是正确的图片没有链接。
最佳答案
将 onclick
设置为链接是错误的。 onclick
需要是有效的 JavaScript。但是,由于您似乎正在尝试“取消链接”这些照片,因此最好完全删除 onclick
。
此外,您不能以这种方式设置 href
(除非您希望每个链接都指向同一张照片)。你需要循环。 jQuery 的 .each()
应该可以解决这个问题。就像这样:
$("p.listphotos a img").each ( function () {
//-- `this` is each target image, one at a time
var jThis = $(this);
//-- More robust replace
var bigLink = jThis.prop ("src").replace (/\bmin\b/i, "max");
//-- The img parent is the link we're after.
jThis.parent ().prop ("href", bigLink).removeProp ("onclick");
} );
<小时/>
请注意prop
and removeProp
are the correct way to kill an onclick
。但是,如果您在某些浏览器中检查页面源,该属性仍然存在。别担心,onclick
将不再起作用。
关于javascript - 将页面的每个onclick替换为img src链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24797451/