[英]how to use $(this) with foreach in javascript using jquery
我正在使用Javascript進行個人項目,以使人們可以在Scrabble中創建“夢想中的戲劇”表。 這是鏈接: http : //psyadam.neoclaw.net/tables8.html
我目前正在嘗試允許用戶編輯夢幻劇。
這是我的代碼:
function editRow(e)
{
var eventEl = e.srcElement || e.target,
parent = eventEl.parentNode
parent = parent.parentNode
var test = $(parent.cells[0]).text()
$('tr').each(function(){
$(this).children("td:contains(test)").each(
function()
{
pageEnd.innerHTML += "success"
$(this).addClass('selected')
}
)
})
pageEnd.innerHTML += test
//pageEnd.innerHTML += $(parent.cells[3]).text()
insertRow()
}
// insertRow assumes that the correct row in the table has the "selected" class added to it
function insertRow()
{
var Row = $('<tr>').append(
$('<td>').append('<input id="input1">'),
$('<td>').append('<select id="input2"><option value=""></option><option value="Yes">Yes</option><option value="No">No</option></select>'),
$('<td>').append('<select id="input3"><option value=""></option><option value="Natural">Natural</option><option value="1 Blank Used">1 Blank Used</option><option value="2 Blanks Used">2 Blanks Used</option></select>'),
$('<td>').append('<select id="input4"><option value=""></option><option value="vs Computer">vs Computer</option><option value="Online Game">Online Game</option><option value="Friendly Game">Friendly Game</option><option value="Club Game">Club Game</option><option value="Tournament Game">Tournament Game</option></select>'),
$('<td>').append('<input id="input5">')
)
$("#myTable tr.selected").after(Row)
}
現在,我只是想讓我的代碼在表中插入一行。 我試圖通過使用代碼$(this).addClass('selected')
來標記用戶選擇的行,然后在我的插入函數中使用它來插入行來做到這一點。 但是,似乎什么也沒有發生。 我正在使用pageEnd.innerHTML += "success"
作為調試工具,以查看它是否到達那里。 出乎意料的是,它只打印一次時就打印兩次成功,因為在我運行的測試中,每個單詞都是唯一的。
無論如何,我不知道為什么它不起作用。 任何幫助表示贊賞。 謝謝,〜亞當
嘗試這個:
function editRow(e) {
var eventEl = e.srcElement || e.target,
parent = eventEl.parentNode
parent = parent.parentNode
var test = $(parent.cells[0]).text()
$('tr').each(function(){
var outerThis = this;
outerThis.children("td:contains(test)").each(
function()
{
pageEnd.innerHTML += "success";
$(this).children().css('text-align', 'center');
}
)
})
pageEnd.innerHTML += test
//pageEnd.innerHTML += $(parent.cells[3]).text()
insertRow()
}
我將外部this
設置為可以使用的變量。 同樣, textAlign
不是jQuery函數。 您需要使用.css()
,然后在其中指定text-align
。
您有兩種選擇可以實現此目的:
正如其他人所建議的那樣,第一個建議是通過保留外部變量this
,然后使用此變量:
$('tr').each(function() {
var outerThis = this;
// inside another loop (not sure about children method, just an example)
$(outerThis).children("td:contains(test)").each(function() {
// do something with outerThis to operate on further
});
});
使用Javascript的bind()
方法的另一種選擇:
$('tr').each(function(i, trElement) {
// this == trElement
// inside another loop
$(outerThis).children("td:contains(test)").each(function(index, tdElement) {
$(this) // will be now tr element
$(tdElement) // will be td element
}.bind(this));
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.