我正在尝试使用jQuery抓取图像的来源。但是,当我记录结果时,它返回未定义。这是我的代码:



$(document).ready(function() {
  $(".btn-expand").on("click", function() {
    var img = $(".img-" + "num" + " img").attr("src");
    console.log(img);
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <div class="col-md-12 img-banner img-2">
    <img src="assets/img/placeholder-banner.png" alt="Banner 2">
    <div class="overlay overlay-2">
      <div class="overlay-contents">
        <h2>Name2</h2>
        <h3>Caption2</h3>
        <a href="" class="btn-expand" overlay-data="2">View</a>
      </div>
    </div>
  </div>
</div>

最佳答案

$(".img-" + "num" + " img")


完全等同于

$(".img-num img")


我相信您是说"num"是一个名为num的变量,其值是目标图像的编号,而不是硬编码的字符串:



$(document).ready(function() {
  $(".btn-expand").on("click", function(event) {
    var num = $(event.currentTarget).attr('overlay-data')
    var img = $(".img-" + num + " img").attr("src");
    console.log(img);
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <div class="col-md-12 img-banner img-2">
    <img src="assets/img/placeholder-banner.png" alt="Banner 2">
    <div class="overlay overlay-2">
      <div class="overlay-contents">
        <h2>Name2</h2>
        <h3>Caption2</h3>
        <a href="#" class="btn-expand" overlay-data="2">View</a>
      </div>
    </div>
  </div>
</div>

关于javascript - jQuery attr(“src”)返回未定义,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48130827/

10-13 00:36