[英]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.