2010-01-25 7 views
0

안녕하세요, 아래 스크립트의 jquery를 사용하여 클래스 이름을 동적으로 가져올 수 있는지 궁금합니다.jquery를 사용하여 클래스 이름을 가져 오는 방법은 무엇입니까?

HTML 출력은 다음과 같습니다

<div id="main-info-1" class="maini"> 
    <p>this is a paragraph.</p> 
</div> 

을 그래서, 내가 위에서처럼 클래스 이름을 얻을 동적으로 대신 하드 코딩하기 위해 노력하고있어.

나는 JQuery와 스크립트에서 클래스 이름을 얻을 필요가 두 부분이 있습니다

1.) pc.children('div.maini').remove(); 

2.) maini_s = $('div.maini').remove(); 

당신이 하드 코딩 클래스 'maini'을 볼 수 있고 클래스 이름을 동적으로 가져 오는 방법을 확실 메신저 수 있듯이이 그것을 스크립트에 올바로 넣으십시오.

JQuery와 파일 :

<script type="text/javascript"> 
// make them global to access them from the console and use them 
// in handlePaginationClick 
var maini_s; 
var num_of_arts; 
var ipp; 

function handlePaginationClick(new_page_index, pagination_container) { 
    var pc = $(pagination_container); 
    pc.children('div.maini').remove(); 
    for(var i=new_page_index*ipp; i < (new_page_index+1)*ipp ;i++) { 
     if (i < num_of_arts) { 
       pc.append(maini_s[i]); 
     } 
    } 
    return false; 
} 

$(document).ready(function() { 
    maini_s = $('div.maini').remove(); 
    num_of_arts = maini_s.length; 
    ipp = 3; 

    // First Parameter: number of items 
    // Second Parameter: options object 
    $("#News-Pagination").pagination(6, { 
     items_per_page:ipp, 
     callback:handlePaginationClick 
    }); 
}); 


     </script> 

이에 어떤 도움이 좋지 않을까, 감사합니다. 클래스 이름을 얻기 위해 jQuery를 사용

+0

어디에서 동적으로 고정합니까? 방금 글로벌 js var해야합니까? – Jage

+0

hasClass() addClass() removeClass() 및 toggleClass()에 대한 예제를 살펴보십시오. –

답변

6

.

당신은 jQuery를 또는 일반 자바 스크립트를 사용하여 클래스 이름을 얻을 수 있습니다 : 이것은 당신이 요소의 class 속성의 문자열 값을 줄 것이다

// jQuery 
$myElement.attr('class'); 

// javascript 
myElement.className 

. 요소에 둘 이상의 클래스가있는 경우 (예 : <div class="foo bar">) 위의 메서드는 "foo bar"을 반환합니다. 당신이 요소에 클래스의 배열을 원하는 경우에, 당신은 단지 공백에 결과를 분할해야합니다

var classes = myElement.className.split(/\s+/); 
// classes = ["foo", "bar"] 
2

과 같이 작동합니다 : 그것은 당신이 정확히 후하는지에 따라 달라집니다

$('#main-info-1').attr('class'); 
0

추가하고 여러 클래스를 사용할 때 공백에 분할에 대해 걱정할 필요없이 클래스를 제거 감지 할 수 있습니다. 그리고 편리한 토글도 있습니다 :

// toggle example 
$('ele').toggleClass('active'); 

// toggle with optional bool parameter 
$('ele').toggleClass('active', isActive); 

// detect/add/remove classes without having to split on blank space " " 
if ($('ele').hasClass('dull')) 
    $('ele').removeClass('dull').removeClass('productive'); 
else 
    $('ele').addClass('fun').addClass('profitable'); 
관련 문제