简体   繁体   中英

Best way to store JQuery variables?

I just want to get some thoughts on storing variables for JQuery's use.

Example

Here JQuery would use the the value of the video_id hidden input, and then voteup the video by the video_id .

 <form class='voteup' action='' method='post'>
   <input type="hidden" name='video_id' value='<?php echo $video_id; ?>' />
   <input type='submit' value='Vote Up' />
 </form>

Note: This is just an example.

But what if I want a link to do the same thing. Where would I store the video_id ?

Obviously, I could store the video_id in the class attribute, but I don't think that this is the best way, especially if I needed to send more than one variable.

Any ideas on this?

I must mention that I'm only looking for XHTML valid ways.

You can use the jQuery data method to attach arbitrary data to an element. In your case, if I've understood what you're trying to do correctly, you probably want to do something like this:

$(document).ready(function() {
    $("#yourLink").data("video_id", "<?php echo $video_id; ?>");
});

As you are looking for valid XHTML solutions, you can't use the HTML5 data-* attributes. If that was the case, you could add the attribute value directly on the element (as you've done with the value attribute in your example).

The data method does not require a corresponding data-* attribute to be present on the element, so this will still allow you to write valid XHTML.

If you digg HTML5 you should go for the data attribute.

http://ejohn.org/blog/html-5-data-attributes/

In an HTML 5 page, you can use "data-" attributes for things like that:

<img src='http://placekitten.com/100/100' data-video-id='whatever'>

Then, from jQuery:

$('img').click(function() {
  var video = $(this).data('video-id'); // 'videoId' also works here
});

If you're (tragically) stuck with strict XHTML, well, you're stuck. For an <a> tag you could possibly use the "rel" attribute I guess. In general "class" is probably in fact the thing to do. The convention I've used for name-value pairs in the "class" is to separate them with a colon and then extract them via regex:

<sometag class='whatever videoId:video22 something'>

and then:

$('sometag').click(function() {
  var videoId = this.className.replace(/videoId:(\S*)/, '$1');
  // ...
});

Perhaps use the rel attribute, and grab it in jQuery using the .attr() method.

var myVar = $('#link_id').attr('rel');

http://api.jquery.com/attr/

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