【问题标题】:alert an src by clicking a button in jquery通过单击 jquery 中的按钮来提醒 src
【发布时间】:2019-02-03 08:00:53
【问题描述】:

这是我的 jquery 代码;但它给了我(未定义)。

$(document).ready(function(){
    $('.items > tbody > tr').click(function() {
        var src = $(this).find('a[title="View"]').attr('src');
        alert (src)
    });
});

HTML 代码是:

<table class="items">
<tbody>
    <tr>
        <td></td>   
        <td></td>   
        <td></td>   
        <td></td>
        <a title='View' src="main.php"></a> 
        <a title='find' src="index.php"></a>    
    </tr>
</tbody>

【问题讨论】:

  • 请发布更多的html,包括.items class。

标签: jquery url var src attr


【解决方案1】:

问题是您的锚标签&lt;a&gt; 不在&lt;tr&gt; 系列中。您必须将它们带入&lt;td&gt;,以便它们成为&lt;tr&gt; 的孩子

$(document).ready(function(){
    $('.items > tbody > tr').click(function() {
        var src = $(this).find('a[title="View"]').attr('src');
        alert (src)
    });
});
tr{
  background:#ff8800;
  height:40px;
}
table{
  width:100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="items">
<tbody>
    <tr>
        <td></td>   
        <td></td>   
        <td></td>   
        <td></td>
        <td>
          <a title='View' src="main.php"></a> 
          <a title='find' src="index.php"></a>
        <td>
    </tr>
</tbody>

【讨论】:

    【解决方案2】:

    我的猜测是你的 this 超出了范围。

    尝试像这样将作用域传递给你的函数:

    $(document).ready(function(){
        $('.items > tbody > tr').click(() => {
            var src = $(this).find('a[title="View"]').attr('src');
            alert (src)
        });
    });
    tr{
      background:#ff8800;
      height:40px;
    }
    table{
      width:100%;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table class="items">
    <tbody>
            <td></td>   
            <td></td>   
            <td></td>  
              <a title='View' src="main.php"></a> 
              <a title='find' src="index.php"></a>
            <td></td>
            <td></td>
    </tbody>

    【讨论】:

    • 查看扩展代码。这个解决方案绝对有效。
    猜你喜欢
    • 2019-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 2011-09-04
    • 1970-01-01
    相关资源
    最近更新 更多