[javascript] 클래스별로 jQuery 계산 요소-이것을 구현하는 가장 좋은 방법은 무엇입니까?

내가하려는 것은 현재 페이지의 모든 요소를 ​​동일한 클래스로 계산 한 다음 입력 양식의 이름에 추가하는 데 사용하는 것입니다. 기본적으로 사용자가 a를 클릭 <span>한 다음 동일한 유형의 항목에 대해 다른 것을 추가 할 수 있습니다. 그러나 jQuery / JavaScript로 이러한 모든 것을 간단히 계산할 수있는 방법을 생각할 수 없습니다.

그런 다음 항목을 다음과 같이 이름을 지정하려고했습니다. name="whatever(total+1)"누구 라도이 작업을 수행 할 수있는 간단한 방법이 있다면 JavaScript가 내 모국어가 아니기 때문에 매우 감사 할 것입니다.



답변

그냥 다음과 같아야합니다.

// Gets the number of elements with class yourClass
var numItems = $('.yourclass').length


참고로, 실제로 수행 할 작업이 있는지 확인하기 위해 jQuery 객체에 대한 많은 함수 호출을 연결하기 전에 length 속성을 확인하는 것이 유리합니다. 아래를보십시오 :

var $items = $('.myclass');
// Ensure we have at least one element in $items before setting up animations
// and other resource intensive tasks.
if($items.length)
{
  $items.animate(/* */)
    // It might also be appropriate to check that we have 2 or more
    // elements returned by the filter-call before animating this subset of 
    // items.
    .filter(':odd')
      .animate(/* */)
      .end()
    .promise()
    .then(function () {
       $items.addClass('all-done');
    });
}


답변

같은 클래스를 참조하는 요소 수를 얻는 것은 이렇게 간단합니다.

<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
        <script type="text/javascript">

            $(document).ready(function() {
                alert( $(".red").length );
            });

        </script>
    </head>
    <body>

        <p class="red">Test</p>
        <p class="red">Test</p>
        <p class="red anotherclass">Test</p>
        <p class="red">Test</p>
        <p class="red">Test</p>
        <p class="red anotherclass">Test</p>
    </body>
</html>


답변

var count = $('.' + myclassname).length;


답변

계산 :

$('.yourClass').length;

잘 작동합니다.

변수에 저장하는 것은 다음과 같이 쉽습니다.

var count = $('.yourClass').length;


답변

HTML :

<div>
    <img src='' class='class' />
    <img src='' class='class' />
    <img src='' class='class' />
</div>

자바 스크립트 :

var numItems = $('.class').length;

alert(numItems);

내부 전용 div에 대한 바이올린 데모


답변

시험

document.getElementsByClassName('myclass').length


답변