【问题标题】:Can't select changed image src with jquery无法使用 jquery 选择更改的图像 src
【发布时间】:2020-10-29 01:23:27
【问题描述】:

我已经通过 jquery 更改了 img src,但是现在我想在您单击图像时打开一个模式,并且由于某种原因我无法选择更改后的 img,当我单击它时,操作会转到图像在 src 更改之前。 这是我的代码:

HTML:

        <div class="tipoplantas text-center">
            <button id="botao2" type="button" class="botaoplantas">1</button>
            <button id="botao1" type="button" class="botaoplantas">2</button>
        </div>
        <div class="imagemplanta text-center">
            <img id="imagemplanta" src="img/infinity/planta1.jpg" class="img-fluid">
        </div>

JAVASCRIPT:

    // Switch Images

    $('#botao1').click(function(){
      $('#imagemplanta').each(function(){
         $(this).animate({
           opacity: 0
         }, 500, function(){
          $('#botao1').addClass('selected')
          $('#botao2').removeClass('selected')
            $(this).attr('src', '/img/infinity/planta1.jpg');
         });
        $(this).animate({
          opacity: 1
        }, 500);
      });
   });
    $('#botao2').click(function(){
      $('#imagemplanta').each(function(){
         $(this).animate({
           opacity: 0
         }, 500, function(){
            $('#botao2').addClass('selected')
            $('#botao1').removeClass('selected')
            $(this).attr('src', '/img/infinity/planta2.jpg');
         });
        $(this).animate({
          opacity: 1
        }, 500);
      });
   });

   // Test
   $("img[src$='img/infinity/planta2.jpg']").click(function() {
    alert('234');
  })
  $("img[src$='img/infinity/planta1.jpg']").click(function() {
    alert('123');
  }) 

所以每当我切换到第二张图片并点击顶部时,它会发送警报“123”而不是我想要的“234”。

【问题讨论】:

  • 页面加载时点击分配完成,不能动态工作
  • 有什么办法解决这个问题?

标签: javascript html jquery


【解决方案1】:

你可以这样做

$('#imagemplanta').click(function()
  {
  let imgSrc = $(this).attr('src')
    , imgIdx = imgSrc.lastIndexOf("/") + 1
    , imgName = imgSrc.substr(imgIdx)
    ;
  if (imgName === 'planta1.jpg')  alert('123')
  else                            alert('234')
  })

【讨论】:

  • 非常感谢
猜你喜欢
  • 2012-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-12
  • 2023-04-07
  • 1970-01-01
  • 2021-07-21
相关资源
最近更新 更多