开发者

simplified and clean way to substitute variable values in JQuery id selector

In my application I have a mark up like these

    <div id="divLeft" style = " width: 300px; border: 1px solid red; float: left" onclick="DoThis('textId')"> 
          <input type="text" id="textId" />
    </div>
    <div id="divRight" style = " width: 600px; border: 1px solid red; float: right" onclcick="DoThat()">    
    </div>

and in the java script event handler code I have to retrieve textId element开发者_StackOverflow for which i use the id selector as

function DoThis(id){

//some code goes here
$("#"+id).show();
//some code goes here

}

and there are hundreds of places where am doing string concatenation like "#"+somID, this looks bad to me. I wanted to know is there some way or jquery selector API like $.id(someID) or something which would avoid this string concatenation?

Regards, Jeez


Create a wrapper:

var $$ = function( id ) { return jQuery('#' + id); };

function DoThis(id){

    $$( id );

}


To avoid string concatenation, you could use the native function that is faster than jQuery css id selector.

jQuery.extend({
    byId: function(id) {
      return jQuery(document.getElementById(id));
    }
});

Usage and Possibility:
$.byId("foo").some_other_jQuery_method();

Working example: http://jsfiddle.net/ZdeBt/

Edit:

You could also have something like the previous answer, using $$ is cool ..

function $$(id) {
  return jQuery(document.getElementById(id));
}
//and
$$("foobar").html("Hey!. Im able to access it");

In this way, you will still get a jQuery object(array) which you can use in the same way as $("#"+id)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜