【问题标题】:How do I make a button determine its table position, call a function and send arguments to it?如何让按钮确定其表格位置、调用函数并向其发送参数?
【发布时间】:2013-09-12 17:48:07
【问题描述】:

我在 HTML/PHP 中创建了一个包含 ID-Name-Button 列的表格。现在,当单击特定行的按钮时,我想调用一个函数来构建一个字符串,然后打开字符串中包含的链接。

我遇到的两个问题是:

  1. 如何获取按钮的当前表格位置并获取前 2 个单元格中的数据?

  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>";

}

【问题讨论】:

  • 你能把你的相关代码放在这里
  • 向我们展示您是如何生成表格的。了解这一点很重要,以便能够让您了解如何继续前进! :)

标签: javascript php button onclick html-table


【解决方案1】:

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 的parentfind

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";
}

不需要将值传递给另一个函数......

【讨论】:

    【解决方案2】:

    使用 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);
     });
    

    Demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-20
      • 1970-01-01
      • 2011-05-20
      • 1970-01-01
      • 2022-06-14
      • 2017-06-12
      相关资源
      最近更新 更多