3 回答

TA貢獻1891條經驗 獲得超3個贊
您無需使用 jQuery 即可完成此操作。
let index = [...this.parentElement.childNodes].indexOf(this);

TA貢獻1818條經驗 獲得超3個贊
問題是因為this第一行引用了windowElement,所以find('.days')不返回任何內容。因此索引始終為-1。
index()要解決此問題,只需在單擊的元素上使用:
const $days = $("#calendar .day").on("click", function() {
console.log("index", $(this).index());
});
td {
padding: 10px;
border: solid black 1px;
}
table {
border-collapse: collapse;
}
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<div id="calendar">
<table>
<tr>
<td id="1" class="day">1</td>
<td id="2" class="day">2</td>
<td id="3" class="day">3</td>
<td id="4" class="day">4</td>
<td id="5" class="day">5</td>
<td id="6" class="day">6</td>
<td id="7" class="day">7</td>
</tr>
</table>
</div>

TA貢獻1786條經驗 獲得超11個贊
當你構建 jQuery 元素列表時.day
,它應該是
const $days = $("#calendar .day");
在全局級別,this
將是對它的引用window
,并且 jQuery 將無法使用它。因此,您得到的-1
意思是該元素不在列表中。
- 3 回答
- 0 關注
- 143 瀏覽
添加回答
舉報