简体   繁体   English

无法使jQuery动态选择器正常工作

[英]Can't make jQuery dynamic selector work

I'm working on what seems to be a simple script, making buttons toggle divs in and out of view. 我正在研究似乎是一个简单的脚本,使按钮在视图中切换div。 I've done so before, but this time I'm using dynamic selectors in jQuery, and can't see what is wrong. 我以前做过,但是这次我在jQuery中使用动态选择器,看不到有什么问题。

If I make the call a static one (ie: '#liste_21'), it works like a charm, but as the number of item is not now in advance, I would prefer to get the dynamic version working. 如果我将调用定为静态调用(即:“#liste_21”),则它就像一个超级按钮,但是由于现在尚不预先提供项目号,因此我希望使动态版本能够正常工作。

Any idea what's wrong? 知道有什么问题吗?

Javascript 使用Javascript

    $(document).ready(function() {
        $(".jour").click(function() {
            var jour = $(this).text();
            $('#liste_'+jour).slideToggle();
        });
    });

HTML HTML

<div id="calendrierActivites">
    <div id="nov20" class="jour">
        <span>20</span>
    </div>
    <div id="nov21" class="jour">
        <span>21</span>
    </div>
    <div id="nov22" class="jour">
        <span>22</span>
    </div>
</div>

<div id="liste_20">
    <h2>20 novembre</h2>
</div>
<div id="liste_21">
    <h2>21 novembre</h2>
</div>

<div id="liste_22">
    <h2>22 novembre</h2>
</div>

https://jsfiddle.net/5yqsptry/# https://jsfiddle.net/5yqsptry/#

JS Fiddle JS小提琴

var jour = $(this).find('span').text();

$(this).text() will get the text inside the div with class of jour and you're using the wrong selector. $(this).text()将获得带有jour类的div内的文本,并且您使用了错误的选择器。

jQuery docs on .text() say that .text()上的jQuery文档说

Due to variations in the HTML parsers in different browsers, the text returned may vary in newlines and other white space. 由于不同浏览器中HTML解析器的不同,返回的文本可能在换行符和其他空格中有所不同。

You can simply trim out the whitespace: 您可以简单地修剪空白:

var jour = $(this).text().trim();

You need to trim the jour value 您需要调整行程值

fiddler: https://jsfiddle.net/5yqsptry/3/ 提琴手: https : //jsfiddle.net/5yqsptry/3/

JS: JS:

$(document).ready(function() {

    $(".jour").click(function() {

        var jour = $(this).text();

        $('#liste_'+$.trim(jour)).slideToggle();
    });
});

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

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