开发者

Problem with custom Jquery function (show/hide)

开发者 https://www.devze.com 2023-03-14 01:43 出处:网络
Here is my Javascript: <script type=\"text/javascript\"> $(document).ready(function(){ function showhideitems(itemID){

Here is my Javascript:

<script type="text/javascript">
$(document).ready(function(){
    function showhideitems(itemID){
      if ($(itemID).css('display') == 'none')
      {
        $(itemID).show('slow'); 
      } else { 
        $(itemID).hide('slow');
      } 
    }
});
</script>

When I call the function using:

`<a href="#" onClick="showhideitems('#players1')">`

It doesn't work (the div doesn't 开发者_如何学运维show/hide). What is wrong with the above function?


Put the function outside of ready(). The method you are trying to call is not in scope.

<script type="text/javascript">
$(document).ready(function(){
   //do your startup/initializations here
});

 // This method should be available for you
 function showhideitems(itemID){
      if ($(itemID).css('display') == 'none')
      {
        $(itemID).show('slow'); 
      } else { 
        $(itemID).hide('slow');
      } 
  }
</script>

EDIT - You can try this, but I wouldn't recommend it.

$(document).ready(function() {

  function showhideitems(itemID){
      if ($(itemID).css('display') == 'none') {
        $(itemID).show('slow'); 
      } else { 
        $(itemID).hide('slow');
      } 
  }


  $("#aID").click(function(){
                    event.preventDefault();
                    showhideitems('#players1');
                 });
}); 

Demo here


You defined showhideitems() inside another function. That hides it from the global scope, so your link's onclick handler doesn't know how to find showhideitems. Try removing showhideitems from the other function.

<script type="text/javascript">
  function showhideitems(itemID){
    if ($(itemID).css('display') == 'none')
    {
      $(itemID).show('slow'); 
    } else { 
      $(itemID).hide('slow');
    } 
  }
</script>


I would do something more flexible

I would add a data attribute to the a tag, describing which elements to manipulate. The attribute value can include any valid jQuery selector.

<a href="#" data-hide="#players1">Click me</a>

The the JavaScript will listen for click events on all tags with the data-hide attribute.

$(function(){
    $('[data-hide]').live('click', function(event){
        event.preventDefault();
        var targetEl = $(this).attr('data-hide');
        $(targetEl).toggle('slow');
    });
});

See an example http://jsfiddle.net/emil/8xtpf/

The good thing about this approach is that you can reuse the function to hide different elements, triggered by different anchors. All you need to do it add the data-hide attribute.

0

精彩评论

暂无评论...
验证码 换一张
取 消