在<a> tag on image button Click

时间:2017-03-10 20:13:23

标签: javascript jquery asp.net asp.net-mvc kendo-listview

<td style="float:right;padding-top:5px">
   <a class="testAccId">#:AccountID#</a>                                                                   
   <img id="imgbtn" class="clsimg" onclick="history(event)" src="../Content/images/history.png" />                                 
</td>

I have an anchor tag and an image button, on clicking the image button I need the text in that anchor tag, and that 'td' is in loop, so if I have 2 items, when clicking one the img in 1st tile, I should get the text in from 1 st tile.

I have tried the following options.

 function history(e) {
        var a = $(this).closest('td').next().find('.testAccId').text();
        alert(a);
    }


 function history(e) {

    var a= ($(".imgbtn").closest(".testAccId")).text();
    alert(a);
}

function history(e) {
        var a = $(e.currentTarget).closest('td').next().find('.testAccId').text();
        alert(a);
    }

In the alert I am getting empty or, object object.

Please help me with this.

5 个答案:

答案 0 :(得分:1)

也许你可以尝试类似的事情,但是如果一个例子有点难以说明,但只要结构一致,这应该有效

function history(e) {
 var a = ($(e.target).prev().html());
  alert(a)
}

我也在这里更新了代码,现在应该正常运行^^

答案 1 :(得分:1)

另一种选择:
PS:确保在头部包含Jquery:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">

    $(document).ready(function(){
        $(".clsimg").click(function(){
            alert($(this).parent('td').find('a').text());
        });
    });
</script>

答案 2 :(得分:0)

您可以匹配最近的元素

IEnumerator<T> GetEnumerator()

答案 3 :(得分:0)

删除内联JS并使用更好的点击事件以及.closest().find()的组合

&#13;
&#13;
$(".clsimg").on("click", function() {
  var aText = $(this).closest("td").find("a").text();
  alert(aText);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table>
  <tr>
    <td>
      <a class="testAccId">#:AccountID#</a>
      <img id="imgbtn" class="clsimg" src="//placehold.it/50x50" alt="Desc">
    </td>
  </tr>
</table>
&#13;
&#13;
&#13;

答案 4 :(得分:0)

A和IMG是同一个父母的孩子,他们是兄弟姐妹,所以你只需要这个:

$('.clsimg').click(function() {
    alert($(this).siblings('a').text());
});

JSFiddle working demo