简体   繁体   English

jQuery以选择器开头

[英]jQuery starts with selector

Here's my code: 这是我的代码:

<script type="text/javascript">
    $(document).ready(function () {
        $("[class^=\"hide\"]").hide();
    });
</script>

<div class="hide1">Hide</div>
<div class="show1">Show</div>
<div class="hide2">Hide</div>
<div class="show2">Show</div>
<div class="hide3">Hide</div>
<div class="show3">Show</div>
<div class="hide4">Hide</div>
<div class="show4">Show</div>

But on page load, the hide divs are still visible... what am I doing wrong? 但是在页面加载时, hide div仍然可见...我在做什么错?

Wow... I feel so stupid. 哇......我觉得这么愚蠢。 I spent so much time banging my head against a wall, and only discover the solution after I post here... 我花了很多时间将头撞在墙上,才发现解决方法……

So turns out I was doing everything correctly, but the div s were in a View (I'm using MVC3) that was being loaded after $(document).ready was being called. 所以事实证明我做的一切正确,但是div是在$(document).ready被调用之后加载的View中(我正在使用MVC3)。 Moving the code into the View solved the problem. 将代码移到视图中解决了该问题。

Why do you have separate classes for those? 为什么您要为这些课程设置单独的课程? Why not have a single hide class and set those attributes above (eg "hide1" ) as ids, then your selector can simply be on that class eg $('div.hide') ? 为什么不使用单个hide类并将上面的那些属性(例如"hide1" )设置为id,那么您的选择器可以简单地位于该类上,例如$('div.hide')

See http://jsfiddle.net/2GzpA/1/ for an example. 有关示例,请参见http://jsfiddle.net/2GzpA/1/

EDIT: 编辑:
For your question, you comment: 对于您的问题,您评论:

@Tomgrohl well my code is actually much more complicated. @Tomgrohl我的代码实际上要复杂得多。 I need to be able to hide and show each div individually. 我需要能够分别隐藏和显示每个div。

Why not add a separate class to use for this case? 为什么不添加单独的类以用于这种情况? Then your selector becomes $('div.specificCaseHideClass') . 然后,您的选择器变为$('div.specificCaseHideClass') You can have as many classes as you like and this is a fine example of when to add one. 您可以根据需要选择任意多个类,这是何时添加类的一个很好的例子。

试试这个很简单

$("div:even").hide();

Are you sure that jquery is included? 您确定包含jquery吗? This seems to work: http://jsfiddle.net/6ycbT/ 这似乎可行: http : //jsfiddle.net/6ycbT/

Also, check your js console to see if any errors are getting thrown that might prevent this code from executing 另外,请检查您的js控制台以查看是否抛出任何错误,这些错误可能会阻止该代码执行

switch out the outer quotes by single quotes and it works: 用单引号将外引号切换出来,就可以了:

working fiddle: http://jsfiddle.net/geertvdc/hv4Ls/ 工作提琴: http : //jsfiddle.net/geertvdc/hv4Ls/

code: 码:

$('[class^="hide"]').hide();

You can do : 你可以做 :

$(document).ready(function () {
    $("div[class*=hide]").hide();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM