Ad

Using JQuery To Realize A Click Event For A Span Without Using ID And Name

- 1 answer

How to use jQuery to click the span tab like below?

like this:

<span data-bind="event: {click: toggleshow}, css: {open: more()}" class="">
    Expand<span></span>Search</span>
Ad

Answer

You can add a css class to your span and use the css class as your jQuery selector for registring the click event

<span class="myspan" id="someId">Test</span>
<span class="myspan" id="someOtherId">Test Again</span>

And the jQuery code will be

$(function(){

   $("span.myspan").click(function(e){
     alert("clicked");
     var itemId=$(this).attr("id");
     alert(itemId);
   });

});

Here is a working sample

If you cannot add a css class or other attributes to this span, you might need to use a very wide jQuery selector, which is just the span tag.

$("span").click(function(e){
  alert("clicked");
});

But this click event will be registered to all span's in your page. Another option is to wrap these spans inside a container div and use that in your jQuery selector so that only those span's will be registered for the click event.

<div id="myContainer">
   <span data-bind="event: {click: toggleshow}, css: {open: more()}" class="">
                                                          Expand<span></span>Search</span>
</div>

And the jQuery code to register the click event will be

$(function(){

     $("#myContainer span").click(function(e){
     alert("clicked");

   });

});

Here is a working sample of that.

Ad
source: stackoverflow.com
Ad