我在 HTML/PHP 中创建了一个带有 ID-Name-Button 列的表。现在,当单击特定行的按钮时,我想调用一个函数,该函数为我构建一个字符串,然后打开字符串中包含的链接。
我遇到的两个问题是:
-
如何管理获取按钮的当前表格位置并获取前 2 个单元格中的数据?
-
如何将该数据提供给我的 JavaScript 函数,然后返回它?(我有如何构建URL的功能,我只需要表数据来完成它)
抱歉,如果这些看起来很愚蠢的问题,我对 PHP/Javascript 很陌生。
编辑:以下是我生成表格的方式(顺便说一下,它与Facebook相关,创建了一个朋友列表):
echo "<form id='xy' method='post' action='index.php'>";
echo "<table><tbody><tr><th>ID</th><th>Name</th><th>Button</th>";
for ($i = 0; $i < count($friends[data]); ++$i)
{
echo "<tr><td>".$friends[data][$i]["id"]."</td><td>".$friends[data][$i]["name"]."</td><td><input type='submit' onClick='BuildFeedURL()' value='Nachricht senden (FeedDialog)'/></td></tr>";
}
echo "</tbody></table>";
echo "</form>";
}
Boehmi,没有人是愚蠢的。这两个问题都可以使用JQUERY轻松解决
在此之前,您必须稍微更新您的 HTML:
echo "<tr><td class='fids'>".$friends[data][$i]["id"]."</td><td class="fname">".$friends[data][$i]["name"]."</td><td><input type='submit' onClick='BuildFeedURL(this)' value='Nachricht senden (FeedDialog)'/></td></tr>";
注意添加到TD的类,并this
到buildfeedURL(this);我不知道你为什么使用input type='submit'
,因为你可以使用javascript重定向/重新加载页面。
使用 jquery 的父级并找到:
buildfeedurl(obj) {
var fid = $(obj).parent().parent().find('.fid').html(); // .html() can be replaced with .text() too
var fname = $(obj).parent().parent().find('.fname').html(); // .html() can be replaced with .text() too
{
// do your processing of url building
}
// here you can redirect to your required URL
window.location.href = "http://stackoverflow.com";
}
无需将值传递给另一个函数。
使用jquery很容易
$('button').click(function(){
var td= $(this).closest('tr').find('td');
var id=$(td[0]).html();
var name=$(td[1]).html();
var yourstring = 'id="'+id+'" name="'+name+'"';
alert(yourstring);
});
演示