简体   繁体   中英

jquery - get the value of <tr> in a html table

I have a AJAX created table.

And I need to call a ajax request on the those table which was created through ajax.

Through this I figured out to call the click function on dynamically created HTML element.

Table looks similar like this.

<table>
    <thead>
        <th>Sr. No</th>
        <th>Label</th>
    </thead>
    <tbody>
        <tr value="1">
            <td>1.</td>
            <td>One</td>
        </tr>
        <tr value="2">
            <td>2.</td>
            <td>Two</td>
        </tr>
    </tbody>
</table>

I've assigned value to the tr and now I want to create another ajax request on click of the tr . And based on the value I'm running a query to get the data.

Challenge I'm facing is that I'm not able to get the value of the tr .

Here's the code I tried with.

$(document).ready(function() {
    $('.table').on('click', 'table tbody tr', function() {
        alert($(this).val())
    })
})

Here's the fiddle .

Even in the fiddle I'm unable to get the value of a tr .

Please help me to find where I'm going wrong.

Thanks in advance.

You can use .attr() instead:

$(document).ready(function() {
    $('.table').on('click', 'table tbody tr', function() {
        alert($(this).attr('value'))
    })
})

Updated Fiddle

but actually you should use data-* HTML5 attribute:

<tr data-value="1">

then retrieve it using .data() :

$(document).ready(function() {
    $('.table').on('click', 'table tbody tr', function() {
        alert($(this).data('value'))
    })
})  

Updated Fiddle

尝试使用.attr()

alert($(this).attr("value"));
$(document).ready(function() {
    $('.table').on('click', 'table tbody tr', function() {
        alert($(this).attr("value"));
    })
})

see http://jsfiddle.net/tqQm5/4/

Use text() property of tr instated of val() property.

see this Fiddle

see this code

$(document).ready(function() {
    $('.table').on('click', 'table tbody tr', function() {
       alert($(this).text())
    })
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM