getElementsByTagName setAttribute和regex javascript [英] getElementsByTagName setAttribute and regex javascript

查看:103
本文介绍了getElementsByTagName setAttribute和regex javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用javascript将rel = lightbox放到mediabox支持的某些链接上.

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

我尝试这样做,想知道为什么它不起作用?

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

测试: http://jsbin.com/opica

请帮助编辑此内容: 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>

推荐答案

因此,如果您打开错误控制台(Firefox中的工具->错误控制台),则会在页面上看到两个错误:

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))$)/; 

后面的问题通过按Bart的建议(com\/video)来转义斜线来解决.

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

前者说没有xmlDoc之类的东西.您可能是指该页面的文档,在这种情况下,应将其替换为document.

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.

接下来,整个过程可能无法正常工作,因为您应该在页面加载完成后运行脚本.在jQuery中,它是$(document).ready(function() { /* do your work here */ }),Google如何使用您正在使用的任何框架(mootools-yui?)来实现它.

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

之后,如您所见,在链接上设置了rel属性: http://jsbin.com /elaca/edit .您正在使用的任何库仍然无法工作的事实意味着您使用的是错误的.您甚至都没有链接到您从中下载库的页面,以便有人可以为您查找文档...

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

这篇关于getElementsByTagName setAttribute和regex javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆