div中的两个span元素均不可点击

时间:2018-07-13 07:20:51

标签: javascript jquery html css html5

我在div中有两个span元素-

<div class="search-input">
  <div class="input-categories">
    <span class="comm-input-value">Any unit type </span>
    <span class="icon fa fa-angle-down"></span>
  </div>
</div>

我的jquery代码是-

$('.input-categories').on('click',function(){
        if ($(this).parent().hasClass("open")){
             $(this).parent().removeClass("open");    

        }else {
            $('.input-categories').parent().removeClass('open');
            $(this).parent().addClass('open');

        }
});

问题:只有带有图标的跨度是可单击的。我希望两个跨度都可以单击,而不仅仅是图标跨度。 我该如何实现?请帮助

4 个答案:

答案 0 :(得分:4)

一种优雅的方法是使用jquery的toggleClass方法。

<div class="search-input">
  <div class="input-categories">
    <span class="comm-input-value">Any unit type </span>
    <span class="icon fa fa-angle-down"></span>
  </div>
</div>
<script>
$('.input-categories span').on('click',function(){
        $(this).parent().toggleClass("open");    
});
</script>

答案 1 :(得分:1)

将类放在您的span元素上(如果这是您唯一要单击的span),然后将click绑定到这些span上,如下所示:

<div class="search-input">
  <div class="input-categories">

    <span class="comm-input-value input-span">Any unit type </span>
    <span class="icon fa fa-angle-down input-span"></span>

  </div>
</div>

并且在Jquery中,无需放置if else语句以删除开放使用切换类

$('.input-span').on('click',function(){

             $(this).parent().toggleClass("open");    

});

答案 2 :(得分:1)

$('.input-categories').on('click', function() {
  $(this).parent().toggleClass('open');
});
@import url("https://use.fontawesome.com/releases/v5.1.0/css/all.css");
@import url("https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css");
.input-categories {
  cursor: pointer;
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js"></script>

<div class="search-input">
  <div class="input-categories">
    <span class="comm-input-value">Any unit type </span>
    <span class="icon fa fa-angle-down"></span>
  </div>
</div>

有编写代码的简单方法。为什么少写却能写得多?

答案 3 :(得分:0)

您的代码运行良好。在此示例中进行检查:

$('.input-categories').on('click',function(){
	alert("clicked");
});
.icon{
  margin-left: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.0/css/all.css" integrity="sha384-lKuwvrZot6UHsBSfcMvOkWwlCMgc0TaWr+30HWe3a4ltaBwTZhyTEggF5tJv8tbt" crossorigin="anonymous">
<div class="search-input">
  <div class="input-categories">
    <span class="comm-input-value">Any unit type </span>
    <span class="icon fa fa-angle-down"></span>
  </div>
</div>