使用javascript从网页打开特定链接?

时间:2014-02-15 16:38:09

标签: javascript href tampermonkey getelementsbyclassname

我正在使用Tampermonkey,我似乎无法让jQuery工作,所以这只是Javacript。

我正在尝试使用脚本打开(在新窗口中)网页上项目的链接。我有一个我需要打开的项目列表,以下是这些项目的示例:

<a class="market_listings" href="http://blabla.com/item1">...</a>
<a class="market_listings" href="http://blabla.com/item2">...</a>
<a class="market_listings" href="http://blabla.com/item3">...</a>

   etc.

如您所见,该项目由一个类和一个href定义。该类不是唯一的,但是href是。

我是编程新手,但这是关于如何从页面中专门打开这些链接的想法:

  1. 脚本获取class =“market_listings”的元素, 只是为了缩小页面上hrefs的搜索范围。

  2. 脚本查看这些元素的href是否对应 “http://blabla.com/item *”

  3. 该脚本会打开一个带有该href的新窗口。

  4. 我在编码方面有很多经验,但这就是我启动它的方式,考虑到我只想打开第1和第3项:

    function gethrefandopenwindow() {
             var items = document.getElementsByClassName('market_listings')
    
    //don't know how to code from here
    
             if (*a href of items corresponds to*: 'http://blabla.com/item1')
    
                {
                 *open new window to href of item1*
                 }
    
             if (*a href of items corresponds to*: 'http://blabla.com/item3')
    
                {
                 *open new window to href of item3*
                 }
    
    
    
             else {
                  *refresh the page and start over*
                  }
    }
    

    正如我所说,我几乎没有编程经验,所以我不知道这是否可能,如果是,你愿意帮忙,请向我解释,就像我是一个白痴/新手一样。 :)

    我能想到的唯一另一种方式是:Javascript getElement by href?;由于我的无聊(以及如何从元素中打开特定的href),我不知道如何在我的情况下应用它。

    无论如何,我希望你能帮助我,

    谢谢!

2 个答案:

答案 0 :(得分:0)

看起来你有正确的想法。此功能可能会让您朝着正确的方向前进。

function OpenHrefsInNewWindow() {
    //Get reference to your elements
    var items = document.getElementsByClassName("market_listings");

    for (var i = 0; i < items.length; i++) //Loop through your elements
    {
        //Verify that the href starts with http://blabla.com/item
        if (items[i].href.indexOf("http://blabla.com/item") === 0)
        {
            //If it does, open that URL in a new window.
            window.open(items[i].href, "_blank");
        }
    }
}

另一种写作方式:

function OpenHrefsInNewWindow() {
    //Get reference to your elements
    var items = document.getElementsByClassName("market_listings");
    var i = 0;

    while(i < items.length) //Loop through your elements
    {
        //Verify that the href starts with http://blabla.com/item
        if (items[i].href.indexOf("http://blabla.com/item") === 0)
        {
            //If it does, open that URL in a new window.
            window.open(items[i].href, "_blank");
        }

        i++; //Increment i here.
    }
}

答案 1 :(得分:-1)

可以检索属性值的链接url并稍后执行任何操作

Url = $(this).attr ('href')