单击其alt为示例的图像

时间:2017-09-08 20:32:09

标签: javascript jquery

我有一个包含在div类中的图像。 ' alt'这些图像的属性是不同的。

当我点击' alt'是"示例",它应该带我到其网址为" www.google.com"的网页。

如何使用alt属性绑定到click事件并实现此逻辑?

是否可以使用JQuery或Javascript进行此操作?

这是我的代码,但它不起作用。我该如何修复此代码?

$('img[alt="Example"]').on("click", "img", function (e) {
      e.preventDefault();
      document.location = 'www.google.com';
  });

3 个答案:

答案 0 :(得分:3)

您可以: -

$('img[alt="Example"]').on("click", function (e) {
  e.preventDefault();
  document.location = 'www.google.com';
});

<强> 实施例: -

&#13;
&#13;
$('img[alt="Example"]').on("click", function (e) {
  e.preventDefault();
  document.location = 'www.google.com';
});
&#13;
img{
  cursor:pointer;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img alt="Example" src="https://png.icons8.com/ios/50/007AFF/billie-holiday-filled">
<br><br>
<img alt="MyExample" src="https://a.deviantart.net/avatars/c/r/crussong.png?15">
&#13;
&#13;
&#13;

或者动态创建的图片: -

$(document).on("click", 'img[alt="Example"]', function (e) {
  e.preventDefault();
  document.location = 'www.google.com';
});

<强> 实施例: -

&#13;
&#13;
$(document).ready(function(){
  $('div').html('<img alt="Example" src="https://png.icons8.com/ios/50/007AFF/billie-holiday-filled"><br><br><img alt="MyExample" src="https://a.deviantart.net/avatars/c/r/crussong.png?15">');
});
$(document).on("click", 'img[alt="Example"]', function (e) {
  e.preventDefault();
  document.location = 'www.google.com';
});
&#13;
img{
  cursor:pointer;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

$('img[alt="Example"]').click( function (e) {
      document.location = 'http://www.google.com';
  });

答案 2 :(得分:1)

您有一个不必要的事件委派,您可以通过删除"img"中的.on(删除它,同时将https://添加到网址:

$('img[alt="Example"]').on("click", function (e) {
  e.preventDefault();
  document.location = 'https://www.google.com';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img alt="Example" src="http://placeskull.com/300/300">