Jquery类名称启动选择器在两种不同的情况下不起作用

时间:2018-03-14 04:33:00

标签: javascript jquery html

代码适用于前3个但不适用于最后3个。可能的原因是什么?



$(document).ready(function(){
    $("section[class^='steps-']").hide();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!--hiding-->     

    <section class="steps-1">
    	<h1>Hidden</h1>
    </section>
    <section class="steps-2">
    	<h1>hidden</h1>
    </section>

<!--not hiding-->

    <section class="another-class steps-3">
    	<h1>not hiding</h1>
    </section>
    <section class="another-class steps-4">
    	<h1>not hiding</h1>
    </section>
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:2)

这两个元素还包含另一个类的原因。 在这种情况下,attribute-contains-selector选择器将检查值是否包含给定的子字符串。

$(document).ready(function() {
  $("section[class*='steps-']").hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="steps-1">
  <h1>Hidden</h1>
</section>
<section class="steps-2">
  <h1>hidden</h1>
</section>
<section class="another-class steps-3">
  <h1>not hiding</h1>
</section>
<section class="another-class  steps-4">
  <h1>not hiding</h1>
</section>

答案 1 :(得分:1)

steps-

开头的课程
$("section[class^='steps-']").hide();

包含steps-

的类
$("section[class*='steps-']").hide();

包含steps-但不以steps-

开头的类
$("section[class*=' steps-']").hide();//observe the space

你需要包含:

&#13;
&#13;
$(document).ready(function(){
        $("section[class*='steps-']").hide();
    });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="steps-1">
    <h1>Hidden</h1>
</section>
<section class="steps-2">
    <h1>hidden</h1>
</section>
<section class="another-class steps-3">
    <h1>not hiding</h1>
</section>
<section class="another-class  steps-4">
    <h1>not hiding</h1>
</section>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您应该使用$(document).ready(function(){ $("section[class*='steps-']").hide(); });,它将检查类名字符串

中的包含查询

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="steps-1">
    <h1>Hidden</h1>
</section>
<section class="steps-2">
    <h1>hidden</h1>
</section>
<section class="steps-3 another-class">
    <h1>not hiding</h1>
</section>
<section class="another-class  steps-4">
    <h1>not hiding</h1>
</section>
name fruit
-------------
bill apple
bill orange
lily apple
emma orange

答案 3 :(得分:0)

$(document).ready(function(){
    $("section[class^='steps-']").hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!--hiding-->     

    <section class="steps-1">
    	<h1>Hidden</h1>
    </section>
    <section class="steps-2">
    	<h1>hidden</h1>
    </section>

<!--not hiding-->

    <section class="steps-3 another-class">
    	<h1>not hiding</h1>
    </section>
    <section class="steps-4 another-class">
    	<h1>not hiding</h1>
    </section>