سؤال

كيف يمكنني حساب عدد عناصر TR داخل جدول باستخدام JQUERY؟

وأنا أعلم أن هناك سؤال مماثل, ، لكني أريد فقط الصفوف الإجمالية.

هل كانت مفيدة؟

المحلول

استخدم محدد سيختار كل الصفوف واتخاذ الطول.

var rowCount = $('#myTable tr').length;

ملاحظة: هذا النهج يحسب أيضا جميع TRS من كل جدول متداخل!

نصائح أخرى

كما ترى <tbody> أو <tfoot> في طاولتك، عليك استخدام بناء الجملة التالي أو ستحصل على قيمة غير صحيحة:

var rowCount = $('#myTable >tbody >tr').length;

بدلا من ذلك...

var rowCount = $('table#myTable tr:last').index() + 1;

jsfiddle التجريبي

سيضمن ذلك أن يتم حساب صفوف طاولة متداخلة أيضا.

حسنا، أحصل على صفوف أسقف من الطاولة واحصل على طول تلك المجموعة:

$("#myTable").attr('rows').length;

أعتقد أن jQuery يعمل أقل.

ها هي بلدي تأخذ على ذلك:

//Helper function that gets a count of all the rows <TR> in a table body <TBODY>
$.fn.rowCount = function() {
    return $('tr', $(this).find('tbody')).length;
};

الاستعمال:

var rowCount = $('#productTypesTable').rowCount();

حصلت على ما يلي:

jQuery('#tableId').find('tr').index();

كنت بحاجة إلى طريقة للقيام بذلك في عودة أجاكس، لذلك كتبت هذه القطعة:

<p id="num_results">Number of results: <span></span></p>

<div id="results"></div>

<script type="text/javascript">
$(function(){
    ajax();
})

//Function that makes Ajax call out to receive search results
var ajax = function() {
    //Setup Ajax
    $.ajax({
        url: '/path/to/url', //URL to load
        type: 'GET', //Type of Ajax call
        dataType: 'html', //Type of data to be expected on return
        success: function(data) { //Function that manipulates the returned AJAX'ed data
            $('#results').html(data); //Load the data into a HTML holder
            var $el = $('#results'); //jQuery Object that is holding the results
            setTimeout(function(){ //Custom callback function to count the number of results
                callBack($el);
            });
        }
    });
}

//Custom Callback function to return the number of results
var callBack = function(el) {
    var length = $('tr', $(el)).not('tr:first').length; //Count all TR DOM elements, except the first row (which contains the header information)
    $('#num_results span').text(length); //Write the counted results to the DOM
}
</script>

من الواضح أن هذا مثال سريع، ولكن قد يكون مفيدا.

لقد وجدت هذا للعمل بشكل جيد حقا إذا كنت ترغب في حساب الصفوف دون حساب th وأي صفوف من الجداول داخل الجداول:

var rowCount = $("#tableData > tbody").children().length;

جرب هذا واحد إذا كان هناك Tbody

بدون رأس

$("#myTable > tbody").children.length

إذا كان هناك رأس ثم

$("#myTable > tbody").children.length -1

استمتع!!!

row_count =  $('#my_table').find('tr').length;
column_count =  $('#my_table').find('td').length / row_count;

var trLength = jQuery('#tablebodyID >tr').length;

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top