尝试在点击图片时重定向到不同的页面
-dontoptimize
-dontpreverify
尝试以下代码:
$('.grid').prepend('<div id="new" style="width:50px;background-color:#1879A9;padding-left:3px;margin-top:10px"><a href="#somelink"><img id="test" src="#somesource"></a></div>');
答案 0 :(得分:0)
<强>被修改强>
我认为您只需创建多个相同的ID元素。
使用ID更改为类,它应该可以正常工作。
<强>被修改强>
根据提问者的评论进行修改
$('.grid').each(function(event){
if($(this).find('.test').length > 0) return false;
var _html = '<div style="width:50px;background-color:#1879A9;padding-left:3px;margin-top:10px"><a class="link" href="'+$(this).data('url')+'"><img class="test" src="'+$(this).data('image')+'"></a></div>';
var new_node = $(_html);
$(this).prepend(new_node);
new_node.find('.test').click(function(event){
event.preventDefault();
alert($(this).attr('src'));
// redirect here
// window.location.href = $(this).parent().attr('href');
})
})
.grid{
width:40px;
height:40px;
background-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="grid" data-url="x.x.x" data-image="http://x.x.x"></div>
<br/>
<div class="grid" data-url="y.y.y" data-image="http://y.y.y"></div>
<br/>
<div class="grid" data-url="z.z.z" data-image="http://z.z.z"></div>
<br/>
<div class="grid" data-url="a.a.a" data-image="http://a.a.a"></div>
答案 1 :(得分:0)
也许是这样的:
$('.grid').on('click', window.location.href = 'page_url');
答案 2 :(得分:0)
首先你要使用id的类,(当多个元素的id相同时语义错误)
还可以在点击图片时重定向到您的页面, 首先单击网格时阻止默认操作,因此直接单击链接时不会重定向。
然后使用$(this).parent(&#34; a&#34;)。attr(&#34; href&#34;)以编程方式获取父标记图像和perfom重定向的链接; window.location.href
见下面的代码:
$('.grid').prepend(
'<div class="new" style="width:50px;background-color:#1879A9;padding-left:3px;margin-top:10px"><a href="https://stackoverflow.com"><img class="test" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcShuHaRYzsoiz_KpVL5Ite65oK_ILy3p1b5vrZ996D1HFKdAS64"></a></div>');
$('.grid').on('click', '.test', function(e) {
e.preventDefault();
var urlRedirect = $(this).parent("a").attr("href");
console.log("redirecting to ..."+ urlRedirect);
// this will redirect after 2 sec
setTimeout(function(){
window.location.href = urlRedirect;
},2000)
});
&#13;
.test {
width:20px;
height:20px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="grid"></div>
&#13;