我正在尝试访问传单地图中的按钮。该按钮是使用插件“easy-button”创建的。 我的主要目标是查看按钮是否已被点击(处于活动状态),我将在另一个功能中使用它进行验证,此处未显示。
这是按钮的html在浏览器调试器中的样子(我相信html是由插件创建的?)。
点击之前
<button class="easy-button-button leaflet-bar-part leaflet-interactive add-markers-active" title="Vis crosshair">
<span class="button-state state-add-markers add-markers-active">
<span class="fa fa-crosshairs fa-lg"></span>
</span>
</button>
点击后
<button class="easy-button-button leaflet-bar-part leaflet-interactive remove-markers-active" title="Fjern crosshair">
<span class="button-state state-remove-markers remove-markers-active">
<span class="fa fa-undo"></span>
</span>
</button>
此单击功能访问该按钮并显示“单击按钮”但if语句未通过。我在浏览器中使用复制CSS路径获得了按钮,但它似乎很长。
$("div.leaflet-bar.easy-button-container.leaflet-control > button > span").click(function(){
alert("Button was clicked");
if
($('span').hasClass('fa fa-crosshair fa-lg'))
{
alert('My button has active class')
}
});
关于我做错了什么建议?
答案 0 :(得分:1)
此
if($('span').hasClass('fa fa-crosshair fa-lg'))
不会定位您期望的span
。
你想要
if($('span',this).hasClass('fa fa-crosshair fa-lg'))
定位您点击的范围的子跨度
答案 1 :(得分:1)
运行此示例,希望它有所帮助:
$(document).ready(function() {
// My example to trigger the click on buttons..
$("button > span > span").click(function(){
alert("Button was clicked");
if (
//$(this).hasClass('fa') && <-- You don't need it, both have it
$(this).hasClass('fa-crosshairs') &&
$(this).hasClass('fa-lg')
) {
alert('My button has active class');
} else {
alert('Ops..');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Unclicked -->
<button class="easy-button-button leaflet-bar-part leaflet-interactive add-markers-active" title="Vis crosshair">
<span class="button-state state-add-markers add-markers-active">
<span class="fa fa-crosshairs fa-lg">click me</span>
</span>
</button>
<!-- Clicked -->
<button class="easy-button-button leaflet-bar-part leaflet-interactive remove-markers-active" title="Fjern crosshair">
<span class="button-state state-remove-markers remove-markers-active">
<span class="fa fa-undo">clicked</span>
</span>
</button>