getElementsByTagName setAttribute 和正则表达式 javascript
我想使用 javascript 将 rel=lightbox 放到 mediabox 支持的一些链接中。
我尝试这个并想知道为什么它不起作用?
请帮助编辑此: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>
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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因此,如果您打开错误控制台(Firefox 中的工具 -> 错误控制台),您将在页面上看到两个错误:
后者通过按照 Bart 建议转义斜线来修复(
com\/video
)。前者说不存在
xmlDoc
这样的东西。您可能指的是页面的文档,在这种情况下,您应该将其替换为document
。接下来,整个事情可能无法正常工作,因为您应该在页面加载完成后运行脚本。在 jQuery 中,它是
$(document).ready(function() { /* do your work here */ })
,谷歌如何使用您正在使用的任何框架(mootools-yui? )。之后,如您所见,在链接上设置 rel 属性: http://jsbin.com/elaca/编辑。事实上,无论您使用什么库仍然无法工作,这意味着您使用了错误的库。您甚至没有链接到下载该库的页面,以便有人可以为您查找文档......
So if you open the Error Console (Tools -> Error Console in Firefox), you'll see two errors on your page:
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 withdocument
.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...
尝试转义
com
和video
之间的/
。Try escaping the
/
betweencom
andvideo
.