当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Strange jQuery behaviour while showing hiding contents

问题描述:

I have a series of html contents called filters which is generated from database. The contents can change dynamically according to the page. I have given css IDs to each main div and appended a number with them while looping. Below is a sample snippet:

<div><a id="filter-1">Brands</a></div>

<div id="filter-op-1">This is option 1</div>

<div><a id="filter-2">Size</a></div>

<div id="filter-op-2">This is option 2</div>

<div><a id="filter-3">Color</a></div>

<div id="filter-op-3">This is option 3</div>

the ids filter-1 and filter-op-1 and so on are generated by the number of loops, so we dont know how much contents on the page will be generated for the filters.

I need to show/hide the filter-op-x contents by a click, so i wrote the following jQuery code:

$(document).ready(function () {

$('div a').click(function() {

var self = $(this);

var cssId = self.attr('id');

var child = $('div#filter-op-'+cssId);

child.toggle();

});

});

Now the problem is that it is not working in this way, but if i remove the cssId in js code and -1, -2 etc in html, it start working, but it is hiding all contents no matter which a i clicked.

I dont understant what is causing this issue. Anybody can explain this problem and give some good advice how to handle it?

JsFiddle is here

Thanks

网友答案:

You need to make some changes in your JS code like this:

 $(document).ready(function () {
   $('div a').click(function() { 
    var self = $(this);
    var cssId = self.attr('id');
    console.log(cssId);  // This gives the `a` id.
    var id = cssId.split("-")[1]; // Split and get the number part
    console.log(id);

    var child = $('div#filter-op-'+id); // append the number part here
    child.toggle();
  });

});

The fiddle: https://jsfiddle.net/sandenay/uk1Lquuh/1/

网友答案:

Problem found : your cssId always return filter-1, filter-2, filter-3 and child become as 'div#filter-op-'+cssId) ==> 'div#filter-op-filter-1 which is produce wrong id of child div.

I have added extra data attribute

Here is my working code:

HTML :

<div><a id="filter-1" data="1">Brands</a></div>
<div id="filter-op-1">This is option 1</div>
<div><a id="filter-2" data="2">Size</a></div>
<div id="filter-op-2">This is option 2</div>
<div><a id="filter-3" data="3">Color</a></div>
<div id="filter-op-3">This is option 3</div>

JS :

$(document).ready(function () {
    $('div a').click(function() { 
        var self = $(this);
        var cssId = self.attr('data');
        var child = $('div#filter-op-'+cssId);
        child.toggle();
    });

});

updated JSFIDDLE example

分享给朋友:
您可能感兴趣的文章:
随机阅读: