我有一个带有一些文字的按钮,我通过innerHTML获得该文本
var helpName = helpButton.parentElement.querySelector('span').innerHTML;
然后我有一些触发手风琴盒的其他按钮
var helpAccordions = modal.getElementsByClassName('accordion');
我想从helpAccordions中选择一个与helpName匹配的元素,并将其设置为var。
<div class="modal-content">
<span class="close">×</span>
<h3 class="modal-title">Help</h3>
<button class="accordion">Key Partners</button>
</div>
<div class="section-header">
<span>Key Partners</span>
<div class="help-icon"></div>
</div>
答案 0 :(得分:1)
只需使用jquery contains()
$(document).ready(function (){
$('button').click(function(){
var a = $('span:Contains('+$(this).text()+')').parent();
//result varible is a
console.log(a.attr('class'))
})
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="modal-content">
<span class="close">×</span>
<h3 class="modal-title">Help</h3>
<button class="accordion">Key Partners</button>
</div>
<div class="section-header">
<span>Key Partners</span>
<div class="help-icon"></div>
</div>
&#13;
答案 1 :(得分:1)
如果你不能使用jQuery,我会让fiddle显示它正常工作,下面是相关代码。
var helpName = helpButton.parentElement.querySelector('span').innerHTML;
var helpAccordions = modal.getElementsByClassName('accordion');
var length = helpAccordions.length;
var myButton;
for(var i = 0; i < length; i++) {
var button = helpAccordions[i];
if(button.innerHTML === helpName) {
myButton = button;
break;
}
}
console.log(myButton) // the button with Key Partners as the text