简体   繁体   中英

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.)

I am generating these buttons dynamically. Currently I pass the data each button needs through onClick.

According to jQuery.click() vs onClick I shouldn't be doing this anymore. 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.)

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! ( Can I add custom attribute to HTML tag? )

The only thing I can think of is to put data in the id attribute then parse it, but that seems very hackish.

Is there a better way?

You may try to use an jQuery on to hook the event on every button. You may put the server Id in an data attribute which is understood by jQuery, without major issues:

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

Then the js:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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