2013-07-20 32 views
0

在Javascript中,我试图自动化一个“onclick()”,但问题是我不知道如何将我的“onclick()”指向该感兴趣的元素。如果该行没有元素ID,如何自动执行“onclick”?

当元素确实有一个ID,虽然,我这样做:

var redbutton = "document.getElementById("red_button")" 

if (redbutton) { 
    redbutton.onclick(); 
    } 

但是这一次,看着网页的HTML,我的“的onclick”的兴趣后,不会有一个ID,所以我不知道如何告诉我的浏览器点击它。 然而,前右其行,有一个ID:

<div id="buttoncolor_pane" style="background-color: rgb(50, 50, 50); position: absolute; width: 400px; height: 200px; top: 30px; left: 0px; z-index: 998; padding-top: 25px; background-position: initial initial; background-repeat: initial initial;"> 
    <div style="width:140px; margin:10px auto; cursor:pointer" onclick="buttoncolor_submit('blue')"> 
    <div style="width:140px; margin:10px auto; cursor:pointer" onclick="buttoncolor_submit('yellow')"> 

有没有一种方法,我可以直接把我的代码到该行,然后告诉它来进行“点击”?

+2

如果这是你的代码,你应该添加一个类或ID,这将是正确的做法。 – user2580076

回答

0

你可以使用querySelectorquerySelectorAll:(可以称为一个节点或document

// get all div elements that are direct children of #buttoncolor_pane 
var nodes = document.querySelectorAll('#buttoncolor_pane > div'); 
if (nodes === null) { 
    return; // or do some other error handling 
} 

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

您可以使用任何您喜欢的查询选择器作为参数。如果您只需要一个,请改用querySelector。它是一样的,但不是返回一个NodeList,而是返回一个Node,所以你可以直接使用它。

在这种特殊情况下,querySelectorAll只会返回一个元素,但我认为你明白了。

或者,如果你真的只是想的第一个孩子,然后用firstChild

document.getElementById('buttoncolor_pane').firstChild.onclick(); 
+0

谢谢!这是完美的作品! – user2599295

0

在jQuery中,你可以做这样的事情触发的第一个孩子点击:

$('#buttoncolor_pane').children().first().click() 
+1

OP没有指定想要使用jQuery。 – Charlie