0

One of the first things I learned in jQuery is the Click() function and how great it is at getting one element to effect another. However, what should I do when I have an array of items (all over my document) that I want to have effect a whole 'nother array of elements once again scatted across my document?

In my strange mind, I am thinking to use data attributes. You can see a VERY simplified version here: http://jsfiddle.net/Qnzpg/

First off, my example on jsfiddle has many a better solutions, I am aware. However, the real application is a bit more complex and requires this method.

I am trying to pass the value of my data attribute as a variable, and have the element that shares that variable be effected (in my example, by having it add a class):

$("#menu [data-cell]").click(function (e){
    e.preventDefault;

    //make the data value a variable
    var $cell = $(this).data();

    //find the other element with the same data value and add the class named "open"
    $('#pages [data-cell='$cell']').addClass('open');
});

I've been fiddling with my jQuery for a very long time now and feel it's best to call in the experts.

What here am I doing wrong?

4

3 回答 3

1

Here you go:

$('#menu li a').each(function() {
    $(this).click(function() {
        var attr = $(this).parents('li').attr('data-cell');
        $('#pages div').each(function() {
            $(this).removeClass('open');
            if($(this).attr('data-cell') == attr) {
                $(this).addClass('open');
            }
        });
    });
});

Fiddle: http://jsfiddle.net/Qnzpg/7/

于 2013-11-05T02:01:40.243 回答
1

You don't have proper syntax for your string concatenation, and I think you want to grab only the value for the data-cell attribute.

var $cell = $(this).data('cell');
$('#pages [data-cell="' + $cell + '"]')

Though to be safe, I wrapped the selector value with double quotes in case the data has a space.

于 2013-11-05T02:02:07.077 回答
1

I made modification to your code and now run correctly

Well first i think that you are wrong because you didn't concatenate the variable $cell but after i realized you dont get the attr data-cell, and you need get the value from data-cell something like this:

var $cell = $(this).attr('data-cell');

and need concatenate $cell like that

$('#pages [data-cell='+$cell+']').toggle('open');
于 2013-11-05T02:04:11.397 回答