javascript - 查找特定标签 a

标签 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();
        }

    }
}

我该怎么做才能匹配条件?

最佳答案

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

当您更改 ID 后,您只需使用 document.getElementById('idOfYourElement')

即可访问它们

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

var current = el[i];

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

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

I think this is the code that stops you. There are no functions called isEqual and contains in JS.

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();
        }

    }
}

关于javascript - 查找特定标签 a,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16548273/

相关文章:

javascript - ID 属性周围有括号?

javascript - 元素排序例程在 Firefox 中有效,但在 Chrome 中崩溃

javascript - 如何使用 Greasemonkey 监控静态 HTML 页面的变化?使用哈希?

javascript - 使用 Javascript 将 SVG 路径点串在一起

javascript - 初始化图表后如何在 LightningChart JS 中添加 defaultAxisXTickStrategy?

javascript - 在 Marionette 中使用变量作为区域名称

javascript - 用 CSS 替换文本/图像 URL

Javascript 错误 - document.getElementById 不是函数

javascript - 在浏览器中加载连续的网页

jquery - 如何根据内部 SPAN 内部的文本删除整个 DIV