getElementsByTagName setAttribute and regex javascript

扶醉桌前 提交于 2019-12-11 19:56:36

问题


i want to put rel=lightbox to some links that mediabox support using javascript.

i try this and wonder why it's not working?

test: http://jsbin.com/opica

please help edit this: http://jsbin.com/opica/edit

<script  type="text/javascript">
var x=xmlDoc.getElementsByTagName("a");
var regexku=/^.+(((twit)|(tweet)|(com/video.+)|(flickr.com.+)|(tube.com.+))|((gif)|(jpe?g)|(png)|(flv)|(swf)|(mp3)|(mp4))$)/;

for(i=0;i<x.length;i++)
 {
a=x[i].getAttribute('href');
if (a.match(regexku) != null)
   {
   x.item(i).setAttribute("rel","lightbox");
   }
 }

</script>

回答1:


So if you open the Error Console (Tools -> Error Console in Firefox), you'll see two errors on your page:

Error: xmlDoc is not defined
Source File: http://jsbin.com/opica
Line: 35

Error: invalid regular expression flag v
Source File: http://jsbin.com/opica
Line: 21, Column: 38
Source Code:
var regexku=/^.+(((twit)|(tweet)|(com/video.+)|(flickr.com.+)|(tube.com.+))|((gif)|(jpe?g)|(png)|(flv)|(swf)|(mp3)|(mp4))$)/; 

The later is fixed by escaping the slash as Bart suggested (com\/video).

The former says there's no such thing as xmlDoc. You probably meant the page's document, in which case you should replace it with document.

Next the whole thing probably won't work because you should run the script after the page is finished loading. In jQuery it's $(document).ready(function() { /* do your work here */ }), google how to do it using the whatever framework you're using (mootools-yui?).

After that as you can see, the rel attribute is set on the links: http://jsbin.com/elaca/edit. The fact that the whatever library you're using still doesn't work means you're using it wrong. You didn't even link to the page you've downloaded the library from so that someone could look up the documentation for you...




回答2:


Try escaping the / between com and video.



来源:https://stackoverflow.com/questions/1576283/getelementsbytagname-setattribute-and-regex-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!