开发者

jQuery - variable strings in function

开发者 https://www.devze.com 2023-04-04 06:38 出处:网络
My html contains many lines like that: 开发者_如何学C<a href=\"#\" id=\"car_small\">Car 1</a>

My html contains many lines like that:

开发者_如何学C
<a href="#" id="car_small">Car 1</a>
<a href="#" id="car_big">Car 2</a>
<a href="#" id="wheels_small">Wheels 1</a>
<a href="#" id="wheels_big">Wheels 2</a>

I would like my script works in that way:

If ID=VARIABLE+'_small' clicked then SlideUp ID=VARIABLE+'_big'

How to do that?

P.S. Also I have created jQuery script:

 $('a').click(function() {

 if($(this).attr('id') == 'car_small'){
  $('#car_big').slideUp('fast', function() { });  }

 });

And this is working in way I would like, but I need copy and paste this code for every link.


    $(document).ready(function() {
     $('a[id$="_small"]').click(function(){
       $('#'+$(this).attr('id').toString().replace('_small','_big')).slideUp('fast', function() { });   
return false;
     });
    });

This is the way to solve this.


$('a[id$="_small"]').click(function(e){
    e.preventDefault();
    var type = $(this).attr('id').split('_', 2)[0];
    $('#'+type+'_big').slideUp('fast');
});


Change your markup a bit:

<a href='#' class='sizeable' data-type='car' data-size='small'>Car 1</a>
<a href='#' class='sizeable' data-type='car' data-size='large'>Car 2</a>
<a href='#' class='sizeable' data-type='wheel' data-size='small'>Wheel 1</a>
<a href='#' class='sizeable' data-type='wheel' data-size='large'>Wheel 2</a>

And your jQuery could be fairly simple:

$('.sizable').click(function(){
    var $this = $(this);
    var type = $this.data('type');
    var size = $this.data('size');

    $('.sizeable[data-type="'+type+'"][data-size="large"]').slideUp('fast');
});

This has the added benefit of making your markup have meaning rather than assigning Ids that have multiple meanings (which destroys the idea of semantic markup).


You could try the endswith selector:

$('a[id$="_small"]')

http://api.jquery.com/attribute-ends-with-selector/

EDIT: and then you can do one of two things to get at the big one:

use .next() if they are in order, or you can get at the id of the selected <a> tag and substring it to get the first part and then pass that with _big to a selector.


You can extand your code using regexp

$('a').click(function() {
  var matches=/(\w+)_small/.exec($(this).attr('id'));
  if(matches.length){
    $('#'+matches[1]+'_big').slideUp('fast', function() { });  }
 });
0

精彩评论

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

关注公众号