2

I have a list of items that I'd like to perform the same action on. They all have separate IDs so I want to be able to pass the name of each one to Jquery so that the action is only performed on that ID. For example:

<a href="#" id="1">one</a>
<a href="#" id="2">two</a>
<div id="#test1"></div>
<div id="#test2"></div>

I want to be able to do something like this:

function doSomething(x) {
     var div=x+'div';
     $(x).click(function() { $.(div).slideDown(); });
}

Any thoughts?

Thanks.

user988129
  • 73
  • 2
  • 3
  • 10

5 Answers5

2

This is how to pass variable in jquery fn

    <title>Test</title>
    <script type="text/javascript">
        $(document).ready(function() {
            $("#but").click(function() {
                var n = $(this).attr("n");
                alert(n);
            });
        });
    </script>
</head>
<body>
    <a id="but" href="#" n="I Love You">Click Here</a>
</body>

neel4soft
  • 507
  • 1
  • 4
  • 12
2
<a href="#" class="x" d="test1">one</a>
<a href="#" class="x" d="test2">two</a>
<div id="test1" class="x"></div>
<div id="test2" class="x"></div>
function doSomething(x) 
{
   $("a.x").click(function()
   { $( "div#" + $(this).attr("d") ).slideDown(); }
   );
}
Gigi
  • 4,953
  • 24
  • 25
2

Use the onclick attribute, that simplifies the code a bit:

<a href="#" id="1" onclick="handleClick(this)">one</a>
<a href="#" id="2" onclick="handleClick(this)">two</a>
<div id="#test1"></div>
<div id="#test2"></div>

function handleClick(x) {
     $('#test'+ x.id).slideDown();
}
Diego
  • 18,035
  • 5
  • 62
  • 66
2

You can pass jQuery element/s directly into the function like so:

var doSomething = function(el){
    el.click(function(){ });
};

// Single element
var $el = $('a.class');
doSomething($el);

// Multiple elements
var $elms = $('a.class, a#id');
doSomething($elms);
elclanrs
  • 92,861
  • 21
  • 134
  • 171
0

You can use data attributes like this to store the data along with html elements and retrieve them using jQuery data() method. Try this.

Html change

<a href="#" data-id="1">one</a>
<a href="#" data-id="2">two</a>
<div id="test1"></div>
<div id="test2"></div>

Use this js

$('a').click(function(){
   $('#test' + $(this).data('id')).slideDown();
});

To retrieve the data attribute value using jQuery data method just pass the second half of the attribute. So in this case passing id to data will give us the id value.

ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124