Home...">

Passing a parameter to a javascript function using CSS Selector

So, in a word, I have a .li set

<ul>
  <li class="lmit_1"><a href="#" >Home</a></li>
  <li class="lmit_2"><a href="#">About us</a></li>
  <li class="lmit_3"><a href="#">Who we are</a></li>
  <li class="lmit_4"><a href="#">Whats new</a></li>
  <li class="lmit_5"><a href="#">Contact Us</a></li>    
</ul>

and my javascript (jQuery)

<script>
  $(".lmit_" + id).click(function () {
    alert(id);
  });
</script>

What I'm trying to do is get any number at the end of the css class as a parameter (e.g. .lmit_3 will allow id = 3), and therefore alert (id) should lead to a popup with number 3? I am new to programming and javascript, so I apologize if the answer looks me in the face ...

+5
source share
6 answers

Demo: http://jsfiddle.net/sFwZj/1/

$('li').click(function () {
  alert($(this).attr('class').split('_')[1]);
});

Your code uses an undeclared variable with a name id, so when you try ".lmit_" + idit should cause an error ReferenceError: id is not defined.

, id not class, , , , , - data-id, $(this).data('id').

+4
$("li").click(function () {
  alert(this.className.split('_')[1]);
});

    <ul>
     <li class="lmit" id="lmit_1"><a href="#" >Home</a></li>
     <li class="lmit" id="lmit_2><a href="#">About us</a></li>

$(".lmit").click(function () {
  alert(this.id.split('_')[1]);
})
+1

, , . , ( ), .

html :

 <ul>
<li class="lmit" data-myattr="1"><a href="#" >Home</a></li>
<li class="lmit" data-myattr="2"><a href="#">About us</a></li>
</ul>

, data-myattr "data-".

       $(".lmit").click(function(){
//you can access it as an attribute
        alert($(this).attr("data-myattr"));
//or you can access it as data
           alert($(this).data("myattr"));
        })

$("ul").delegate("li", "click", function() {
 alert($(this).data("myattr"));
});

lmit html

 <ul>
<li data-myattr="1"><a href="#" >Home</a></li>
<li data-myattr="2"><a href="#">About us</a></li>
</ul>
+1

$('ul li').on('click', function(){
    alert($(this).prop('class').split('_')[1]);
});
0

The answers above are all correct. If you want to capture a position number in <ul>, you have an alternative.

$('li').click(function() {
    alert($(this).index()+1);
});

The advantage is that you do not have to generate class names (if that's all for what they are used)

0
source
$('[li][class^="lmit_"]').click(function () {
  alert($(this).attr('class').split('_')[1]);
});

if you use $ ('li'), if u click on any li that does not have the class limit_, it will also be launched.

0
source

All Articles