0

I'm trying to get the id attr from different onclicks.

Here is the html I have.

<div id="name-1"> 
    <a href="#" class="view">
<div> 

<div id="name-2"> 
    <a href="#" class="view">
<div> 

<p>Name: <span class='name'></span></p>

<script>
$(".view").click(function() {
    var id = $(".view").closest("div").attr("id");
    $('.name').html(id);    
}); 
</script>

When I click the first view I see "name-1" however when I click the second view nothing happens. Also, when I click the second name it shows "name-1". I know this is probably easy to solve but it's friday so I appreciate the help.

4

2 回答 2

4

Change

var id = $(".view").closest("div").attr("id");

to

var id = $(this).closest("div").attr("id");

Right now your current code is looking at the first .view on the page rather than the .view whose click event was triggered.

于 2013-06-28T20:46:12.897 回答
1

原因是您正在使用view类选择器来获取最接近的 id。因此,它会查找第一个可用的view并为您获取 first 的 id DIV

考虑使用$(this)来获取单击元素的最接近的 id。

$(".view").click(function() {
    var id = $(this).closest("div").attr("id");
}); 

不要忘记阅读这篇关于“ jQuery this ”的文章:http ://remysharp.com/2007/04/12/jquerys-this-demystified/

于 2013-06-28T20:50:23.417 回答