开发者

add some javascript inside a html anchor tag href element

Quick javascript question...

I wont bore you with the need for this (lets just say IE) but I need the following HTML:

href="includes/jwplayer/player.swf?3&file=nicki.mp4"

to have a random number generated via javascript where '3' is in the above example. So like:

href="includes/jwplayer/player.swf?[RANDOM NUMBER CODE HERE]&file=nicki.mp4"

I know the js code is:

开发者_如何学PythonMath.floor(Math.random() * 1000)

But how can I fit this in with the Html?

Is the only answer some php (or similar)?

A.


If "fit this in with the Html" means "add a random number to every link that looks like this", then something like this would do it:

$("a[href^=includes/jwplayer/player.swf]").attr("href", function (i, s) {
  return s.replace( /\?\d*&?/, "?" + Math.floor(Math.random() * 1000) + "&" );
})

If it's not <a> elements that carry the href in your case, change the selector accordingly.

The regex says:

\?   # a question mark
\d*  # any number of digits (to replace what's already there)
&?   # an optional ampersand


You could set it via client script, but this will break if the user has JavaScript turned off. It would be better to set it from the server side, which sounds like PHP in your case.


with native javascript you could put in a "not random" link and randomize it with the setAttiribute method native to JavaScript

var r = Math.floor(Math.random() * 1000);
document.getElementById('an-id-of-the-link').setAttribute('href', 'includes/jwplayer/player.swf?' + r + '&amp;file=nicki.mp4');

note that with older versioned browsers selecting the object becomes harder so getElementById is one of the few ways that is safe along most of the browsers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜