2015-11-15 44 views
0

我有這樣的HTML代碼HTML按鈕,點擊它

<div class="form-actions"> 
    <button type="submit" class="btn btn-success">I'm a button! Yayyy!</button> 
</div> 

我需要訪問JS那個按鈕,點擊它。而且我無法爲其添加ID,因爲它位於網頁上。 (我使用tampermonkey/Greasemonkey的BTW)

+0

你使用JQuery呢?如果是,那麼你可以寫'$( 「btn.btn-成功。」)。點擊(); ' –

回答

1

這是很容易使用jQuery做。

$('.btn.btn-success:contains("I\'m a button! Yayyy!")') 

^會是你的按鈕。

如果沒有其他按鈕這個文本,該解決方案可以縮小到:

$('button:contains("I\'m a button! Yayyy!")') 

如果可以有另一個按鈕,這段文字,你要解決的按鈕,完全匹配它,解決辦法是

$(".btn.btn-success").each(function(){ 
    if($(this).html()=="I'm a button! Yayyy!"){ 
     //$(this) there is the button you want 
    } 
}) 
+0

注意,與文本按鈕,「我是一個按鈕!Yayyy!開玩笑的,我不是。」也會被這個選擇器匹配。 – ekuusela

+0

@eku好點的,要進行編輯。 – nicael

+0

第二個解決方案適用於我,第一個,不。 – GameExpertNetwork

0

你可以選擇所有頁面上的元素button,然後使用.filter() method根據自己過濾它們:

Example Here

var buttons = document.querySelectorAll('button'); 
var filteredButtons = Array.prototype.filter.call(buttons, function (el) { 
    return el.textContent.trim() === 'Find based on this text.'; 
}); 

// Click the first button 
filteredButtons[0].click(); 

當然,你的情況,你可以選擇所有.btn-success元素與.form-actions類元素的後代:

var buttons = document.querySelectorAll('.form-actions .btn-success[type="submit"]'); 
var filteredButtons = Array.prototype.filter.call(buttons, function (el) { 
    return el.textContent.trim() === 'Find based on this text.'; 
}); 

// Click the first button 
filteredButtons[0].click(); 
+0

如果你只需要第一個按鈕,你可以使用[Array.prototype.some(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some)和發現匹配時的回調,將匹配分配給變量並返回true以停止迭代。 – ekuusela

+0

@ekuusela好點。我不確定OP想要什麼。 –