我有一个具体问题,我在每行第三列的表格中有一个链接,当用户单击该链接时,他会加载一些ajax并更新页面,我还想发生的是在第二列中链接所在行的列,将 td 的类从 false 更改为 true,并将值从 No 更改为 Yes。
谢谢!
更新! 代码示例:
第二列在点击时仍然没有更新,也许这是因为表格所在的div在点击时被隐藏了?无论如何,这是我尝试过的:
<tr>
<td>00839</td>
<td class="false" style="text-align:left;">No</td>
<td>
<a href="#"
onclick="Element.hide('ajax-instruction-view');;
new Ajax.Updater('ajax-instruction-view', '/tasks/show_ajax/839', {asynchronous:true, evalScripts:true, onComplete:function(request){new Effect.Appear("ajax-instruction-view",{});window.scrollTo(0,0);
link = $(link);
var row = link.up('tr');
var cell = row.down('td').next('td');
cell.update('Yes');},
parameters: 'authenticity_token='encodeURIComponent('SYWsdBTWlz17u9HmPXA2R9WmBfZn67g/IAMGyhHEwXw=')}); return false;"
>
Instructions-Notice Board
</a>
</td>
<td>19/04/10</td>
<td class="false">21/04/10</td>
<td class="false" style="text-align:left;">None.</td>
</tr>
最佳答案
听起来好像在某个时刻,您有对用户单击的链接的引用(要么因为您在其上有一个 click
处理程序,要么因为您正在使用事件委托(delegate)并在单击表格)。从对该链接的引用开始,您可以使用 Prototype 的 DOM 遍历功能来查找第二个表格单元格:
编辑根据您对 rahul 的回复,我会将您的链接 onclick
更改为:
onclick="handleLinkClick(this); return false;"
...这将是handleLinkClick
:
function handleLinkClick(link) {
// Original code (mostly unchanged)
Element.hide('currentdiv');
new Ajax.Updater('someajax', 'ajax.html', {
asynchronous:true,
evalScripts:true,
onComplete: function(request) {
new Effect.Appear("newdiv",{});
window.scrollTo(0,0);
// New code starts here
// Extend the link element
link = $(link);
// Find the row
var row = link.up('tr');
// Find the second column
var cell = row.down('td').next('td');
// Change the cell's "class" and "value" -- I've had to guess a bit at
// what you want to do here
if (cell.hasClassName("true")) {
cell.removeClassName("true").addClassName("false");
cell.update("No");
}
else {
cell.removeClassName("false").addClassName("true");
cell.update("Yes");
}
// End of new code
},
parameters:'authenticity_token=' + encodeURIComponent('SYWsdBTWlz17u9HmPXA2R9WmBfZn67g/IAMGyhHEwXw=')
});
}
使用Element#up
、Element#next
、Element#hasClassName
、Element#addClassName
、Element#removeClassName
和Element#update
;为他们提供文档 here .
需要考虑的可选事项:
- 上面的代码很脆弱,因为如果您更改该单元格的位置(使其成为第三列而不是第二列),它就会失败。您可以使用标记类来查找它。
- 您可以使用
Element#observe
,而不是onclick
属性。 - 您可以使用事件委托(delegate)在表上只放置一个处理程序,而不是在每个链接上放置一个处理程序。
但是上面的应该可以工作。
关于javascript - 使用 Javascript 操作行数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2711235/