getElementsByTagName specific links only

这一生的挚爱 提交于 2019-12-25 09:21:22

问题


I'm trying to use Anarchy Media Player on my site but had to change code a bit because my media files/urls are not in standard format. It pulls the video files now but javascript is finding ALL links and tries to add player to it. I even added id "video" to video link but still finds all links on the page and adds player to it. How can I separate those links to get player added to them only?

Here is the part of the javascript that looks for the links:

var all = document.getElementsByTagName('a');
for (var i = 0, o; o = all[i]; i++) {
    if(o.idName="video" && o.className!="amplink") {
        // Add player code...
    }
}

Thank you for your help.


回答1:


Not sure why you're not just doing this:

var all = document.getElementsByTagName('a');
for (var i = 0, len = all.length; i<len; i++) {
    if(all[i].idName=="video" && all[i].className!="amplink") {
        // Add player code...
    }
}

That should work for you. Note that I stored the value of the array length so you don't have to look it up every iteration. Minimal, but does increase performance slightly.

You were also setting idName to video when you did idName="video" in your if statement, not comparing (that will always return true, which was your problem). Use the double equals operator (==) or the triple equals operator (===) to compare values.




回答2:


Are you sure you don't mean if (o.className == "amplink")?

Besides that what you have is fine (except for the o.idName="video" bit which always returns true): http://jsfiddle.net/VpMVe/




回答3:


you can get elements using querySelectorAll, but it's not supported in older browsers (that would be older then IE8, FF3.5, Opera 10, Chrome 4 and Safari 3.1). It's similar to targetting elements using CSS selectors (and jQuery). here's a demo getting all links with class video to turn red.

function get(selector) {
    return document.querySelectorAll(selector)
}

(function() {
    //get all <a> with class "video"
    var video = get('a.video');

    //for each, turn them red
    for (var i = 0; i < video.length; i++) {
        video[i].style.color = 'red';

        //in your case, do whatever you want for each target here

    }
}())​



回答4:


There is no idName attribute. It's just o.id. And there can only be one id, so that's likely to cause some issues. Also you're assigning it, rather than comparing for equality which always evaluates to true. If you have more than one class, e.g. class="amplink someOtherClass" != amplink will evaluate to true. Better to do a match on the className. Like this:&& !o.className.match(/ampLink/)

Make a video on another class and do matches instead.



来源:https://stackoverflow.com/questions/10133976/getelementsbytagname-specific-links-only

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