开发者

How do I associate an ID with a content of a div?

For example I have a HTML table...

name | grade  | action
bob  | 1.0    | [button class="button" id='1']
jack | 2.0    | [button class="button" id='2']
john | 3.0    | [button class="button" id='3']

When I click the button,

to get the id...

$(function(){
$('.button').click(function()
var buttonid = this.id
});
});

so if I were to press buttonid 1 how do I get the name 'bob' without having开发者_如何学Python to open the database?

Additionally if I press the button how do I get the values in each column? i.e. If I press button 3 how do I get grade 3.0 or get both name and grade?

Script that generates the row of the table

while(){ 
echo '<tr>'; 
echo '<td>'.$name.'</td>'; 
echo '<td>'.$grade.'</td>'; 
echo '<td> <input type="button" class="button" id="'.$id'"</td>';
echo '</tr>';
}


You question is a bit unclear but I think this is roughly what you're looking for:

$('#myTable button').click(function ()
{
    var $tr = $(this).closest('tr'),
        $nameTd = $tr.children('td:first'),
        name = $nameTd.text();

    alert(name);
});

Demo: http://jsfiddle.net/mattball/7XV96/


The most simplest way (in my meaning) is to use the HTML-data attributes on maybe your TR element and have all that data there, then you could just use $(this).closest("tr").data("name"); like:

<tr data-name="bob" data-grade="1.0">
    <!-- all your td-elements -->
</tr>
<tr data-name="jack" data-grade="2.0">
    <!-- all your td-elements -->
</tr>


Try:

$(function() {
    $('button').click(function() {
        var name = $(this).closest('tr').children().first().text();
        // do something with 'name'
    });
});


Your js should be:

$(function(){
    $('button').click(function(){
        var text= $(this).parent().siblings('td:first').text();
    });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜