简体   繁体   English

替代在onClick中传递数据?

[英]Alternative to passing data in onClick?

I have a web page which lists all database records from a certain server. 我有一个网页,其中列出了来自特定服务器的所有数据库记录。 Along side each row are a few buttons which allow you to rename or delete records. 每行旁边都有几个按钮,可用于重命名或删除记录。

INPUT( _value='Rename', _type="button", _class='appbutton', _onclick='renameApplication({0},"{1}")'.format(app.id,app.name))

Which generates something like: 生成如下内容:

<input class="appbutton" type="button" value="Rename" onclick="renameApplication(3,"My Application")"></input>

(The backend templating engine is web2py, but that's not really important.) (后端模板引擎是web2py,但这并不是很重要。)

I am generating these buttons dynamically. 我正在动态生成这些按钮。 Currently I pass the data each button needs through onClick. 目前,我通过onClick传递每个按钮所需的数据。

According to jQuery.click() vs onClick I shouldn't be doing this anymore. 根据jQuery.click()vs onClick,我不应该再这样做了。 But if that is the case, how should I be passing data so that each button click can use dynamic data written server side (the application ID and name in this instance.) 但是,在这种情况下,我应该如何传递数据,以便每次单击按钮都可以使用在服务器端写入的动态数据(本例中为应用程序ID和名称)。

I can't do dom traversal through the record to grab the data because the row structure might change. 我无法遍历记录以获取数据,因为行结构可能会更改。

I can't use custom attributes because I need to support less than HTML 5, and I'm not going to modify the doctype! 我不能使用自定义属性,因为我需要支持的HTML少于5,并且我不会修改doctype! ( Can I add custom attribute to HTML tag? ) 我可以向HTML标签添加自定义属性吗?

The only thing I can think of is to put data in the id attribute then parse it, but that seems very hackish. 我唯一能想到的就是将数据放在id属性中,然后对其进行解析,但这似乎很骇人。

Is there a better way? 有没有更好的办法?

You may try to use an jQuery on to hook the event on every button. 您可以尝试使用jQuery将事件挂接到每个按钮上。 You may put the server Id in an data attribute which is understood by jQuery, without major issues: 您可以将服务器ID放入jQuery可以理解的data属性中,而不会出现重大问题:

<input class="appbutton" type="button" value="Rename" data-id="3"></input>

Then the js: 然后是js:

$('#container').on('click', '.appbutton', function () {
  var serverId = $(this).data('Id'); //this binds to html input
  renameApplication(serverId);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM