2012-08-01 2 views
0

I have folks, 다음 테이블에있는 열의 색인을 확인해야하는 javascript 함수가 있습니다. 문제는 columnName과 테이블의 이름을 비교하는 것입니다. columnName 'ID'로 테스트했으며이 열은 테이블에 있지만 비교가 true가 아니므로 인덱스가 반환되지 않습니다.jquery로로드 한 문자열 비교

내 코드 :

function getColumnIndex(columnName, grid) { 
    console.log("loading column index for column: [" + columnName + "]"); 
    $('div.hDivBox > table > thead > tr > th', grid).each(function(index) { 
     var name = $(this).attr('title'); 
     console.log("Checking cell: [" + name + "]"); 
     if (String(name) == columnName) { 
       return index; 
     } 
    }); 
    console.log("no cell found with name: " + columnName); 
    return -1; 
} 

로그 문 : 컬럼에 대한

로드 열 인덱스 : [ID]
확인 전지 : [ID]
확인 전지 : [이름]
셀 검사 : [설명]
셀 검사 중 : [AddTime]
셀 검사 중 [UpdTime]
는 이름 찾지 셀 : ID

자바 스크립트 함수에 의해 분석되는 HTML의 예는 :

<div class="hDivBox"> 
<table cellspacing="0" cellpadding="0"> 
    <thead> 
     <tr> 
      <th align="center" hidden="" axis="col0" title="ID" style="display: none;"> 
       <div style="text-align: center; width: 30px;">ID</div> 
      </th> 
      <th align="center" axis="col1" title="Name" class=""> 
       <div style="text-align: center; width: 250px;">Name</div> 
      </th> 
      <th align="center" axis="col2" title="Description" class=""> 
       <div style="text-align: center; width: 250px;">Beschreibung</div> 
      </th> 
      <th align="center" axis="col3" title="AddTime"> 
       <div style="text-align: center; width: 120px;">hinzugefügt</div> 
      </th> 
      <th align="center" axis="col4" title="UpdTime"> 
       <div style="text-align: center; width: 120px;">aktualisiert</div> 
      </th> 
     </tr> 
    </thead> 
</table> 

+1

'문자열 (이름)'은 이미 문자열이므로 전송하지 않아도됩니다. 또한 ID, 이름 및 제목에 대해 말할 때 반드시 확인하십시오. 모두 다른 속성입니다. –

+0

이상한. 경우에, 나는'String (name) == String (columnName)'을 시도 할 것인데, 아무 것도 바꿀 것 같지 않다. –

+0

가능한 [Javascript 함수가 요소를 반환하지 못함] (http://stackoverflow.com/questions)/11569516/javascript-function-return-element에 실패) – Bergi

답변

2

다만 일치하도록 jQuery attribute selector 사용하지 제목을 쓰고 자신을 반복하는 대신 index()을 사용하십시오.

function getIndexByTitle(title) { 
return $('th[title="' + title + '"]').index(); 
} 

alert(getIndexByTitle("ID")); 
alert(getIndexByTitle("Name")); 

Example

+0

해당 기능을 알지 못했습니다. 이 똑똑한 솔루션을 가져 주셔서 감사합니다;) –

4

만 기능, 그것은 또한 getColumnIndex() 함수에서 반환하지 않습니다 에서 반환 .each()의 jQuery 함수에 전달 된 익명 함수 내부의 return 문.

대신, 내가 할 줄 다음

function getColumnIndex(columnName, grid) { 
    console.log("loading column index for column: [" + columnName + "]"); 
    var index = -1; 
    $('div.hDivBox > table > thead > tr > th', grid).each(function(i) { 
     var name = $(this).attr('title'); 
     console.log("Checking cell: [" + name + "]"); 
     if (String(name) == columnName) { 
      index = i; 
      return; 
     } 
    }); 
    if(index == -1) 
     console.log("no cell found with name: " + columnName); 
    return index; 
} 

기본 원칙, 즉, 당신은 단순히 외부 범위있어 변수에 올바른 인덱스를 저장하고 오히려 익명 함수에서 인덱스를 돌아보다 따라서 .each() 호출이 완료되면 액세스 할 수 있습니다.

1

당신은 (아마도 false했다 index 경우 각 루프를 중지하고)이 콜백에서 반환하는 기능

.each(function(){ 
    ... 
    return index; 
}); 
return -1; 

.each()를 사용하지만, 탈옥하지 않고 외부 getColumnIndex 함수에서 반환 않습니다! 그래서, 그 사람은 항상 -1을 반환합니다.

빠른 수정 :

function getColumnIndex(columnTitle, grid) { 
    var index = -1; 
    $('div.hDivBox > table > thead > tr:first > th', grid).each(function(i) { 
     if ($(this).attr('title') == columnTitle) { 
      index = i; 
      return false; // break each-loop 
     } 
    }); 
    return index; 
} 
1

당신은 each 반복에서 호출되는 내부 함수에서 반환된다. 이후에 액세스하려면 각 통화 외부에서 색인을 저장해야합니다.

function getColumnIndex(columnName, grid) { 
    var columnIndex; 
    console.log("loading column index for column: [" + columnName + "]"); 
    $('div.hDivBox > table > thead > tr > th', grid).each(function(index) { 
     var name = $(this).attr('title'); 
     console.log("Checking cell: [" + name + "]"); 
     if (String(name) == columnName) { 
       columnIndex = index; 
       // return false to exit the each iteration early 
       return false; 
     } 
    }); 

    if (typeof columnIndex !== "undefined") { 
     return columnIndex; 
    }; 

    console.log("no cell found with name: " + columnName); 
    return -1; 
}