查找特定标签a

时间:2013-05-14 16:26:32

标签: javascript greasemonkey tampermonkey

我的HTML是:

<a id="showSlotsByLocation_" href="#" style="color:blue;" onclick="confirmAppt('28/05/2013','364301');">14.00 - 14.15</a>
<a id="showSlotsByLocation_" href="#" style="color:blue;" onclick="confirmAppt('28/05/2013','364303');">14.15 - 14.30</a>

所有链接上的ID名称相同。这是主要的困难。

我想点击第二个链接我的javascript代码是配置网页浏览器

if (location.pathname == "/abc")
{
    //alert('location found') this is ok found;

    var el = document.getElementsByTagName("a");
    for (var i=0;i<el.length;i++)
    {
        if (el.id == 'showSlotsByLocation_' && el.innerText.isEqual('14.15 - 14.30') && el.outerHTML.contains("confirmAppt('28/05/2013'"))
        {
            alert('link found') \\this condition not match;
            el.onclick();
        }

    }
}

我该如何配合这个条件?

1 个答案:

答案 0 :(得分:3)

您不能拥有两个具有相同ID的元素,ID是唯一的。

如果您更改了ID,则只需使用document.getElementById('idOfYourElement')

即可访问这些ID

编辑: 首先,你需要声明一个“当前”变量,它接受循环中的当前元素,你不能使用el.id,因为el是HTMLElements的集合!对不起我之前没有注意到它。 所以你需要这个(在if语句之前定义变量里面 for循环):

var current = el[i];

现在您已经定义了它,请使用下面的代码更改整行。

if (el.id == 'showSlotsByLocation_' && el.innerText.isEqual('14.15 - 14.30') && el.outerHTML.contains("confirmAppt('28/05/2013'"))
  

我认为这是阻止你的代码。 JS中没有名为isEqualcontains的函数。

if (current.id == 'showSlotsByLocation_' && current.textContent === '14.15 - 14.30' && current.outerHTML.indexOf("confirmAppt('28/05/2013'") !== -1)

最后一件事:innerText不是有效的跨浏览器属性,而是使用textContent。

MDN Reference

更新了JS代码

if (location.pathname == "/abc")
{    
    var el = document.getElementsByTagName("a");
    for (var i=0;i<el.length;i++)
    {
        var current = el[i];
        if (current.id == 'showSlotsByLocation_' && current.textContent === '14.15 - 14.30')//I'm not sure about this one, in case you want it just remove the comment and the last parenthesis && current.outerHTML.indexOf("confirmAppt('28/05/2013'") !== -1)
        {
            alert('link found');
            current.click();
        }

    }
}
相关问题