javascript - click() 方法适用于链接,但不适用于 Javascript 中的按钮

标签 javascript

我编写了一个脚本,通过 chrome 中的开发工具 -> 控制台运行,该脚本会自动添加注释,而不是一次编写和提交一个注释:

 /**
 * Created by keilc on 2/09/2015.
 */
var leaveComment = document.getElementsByClassName('plain leaveComment');
var commentBox = document.getElementsByClassName('botmarg5px feedbacktextarea');
var submit = document.getElementsByClassName('siteButton bigButton');
var comment = "thankyou very much :)";


for(var i = 0; i <= leaveComment.length; i++)
{
    // Click 'leave comment'
    leaveComment[i].click();

    // Leave comment
    commentBox[i].value = comment;

    // Submit the comment
    submit.click();
}

enter image description here

点击();对于 leaveComment 数组中的每个项目成功调用事件,但当它到达提交按钮时,click(); 方法失败并返回 Object does not support property或方法“点击”:

enter image description here

所以我尝试将提交按钮上的 click(); 调用移到 for 循环之外:

for(var i = 0; i <= leaveComment.length; i++)
{
   // Click 'leave comment'
   leaveComment[i].click();

   // Leave comment
   commentBox[i].value = comment;
}

// Submit the comment
    submit.click();

但这给了我无法获取未定义或空引用的属性“点击”错误。

尝试这些不同的方法后,我很困惑为什么 click(); 方法适用于“留下评论”链接,但不适用于提交按钮。

最佳答案

getElementsByClassName()返回所有匹配元素的 NodeList。

Returns an array-like object of all child elements which have all of the given class names. When called on the document object, the complete document is searched, including the root node. You may also call getElementsByClassName() on any element; it will return only elements which are descendants of the specified root element with the given class names.

var submit = document.getElementsByClassName('siteButton bigButton');

如果您只有一个按钮匹配类,请使用

submit[0].click();

如果有多个元素,则迭代它们

for(var i = 0; i < submit.length; i++) {
    submit[i].click();
}

关于javascript - click() 方法适用于链接,但不适用于 Javascript 中的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32350112/

相关文章:

javascript - setInterval 在游戏循环内,未按预期工作

javascript - 如何在进度条上叠加可填写的检查点

javascript - WebGL:将 8 位灰度图像加载到纹理时图像无效

javascript - 在javascript中的文本之间创建空间

php - 有类似的用于绘制图表(如 Google Charts)的库/类吗?

javascript - 在 React 组件中模拟数据

javascript - 用于从字符串创建 JSX 元素的正确 TypeScript 类型

javascript - D3.js折线图,x轴有任意日期,但想按顺序显示它们

javascript - Node中并行/异步的多个分页GET API调用

javascript - Mocha异步执行顺序