开发者

new jQuery selectors

开发者 https://www.devze.com 2022-12-16 19:11 出处:网络
I recently wrote the following selector with a little help from (possbily you) StackOverflow 开发者_Go百科$(\':submit[name=\"Delete\"][value=\"Delete\"]\').click(function() {

I recently wrote the following selector with a little help from (possbily you) StackOverflow

开发者_Go百科$(':submit[name="Delete"][value="Delete"]').click(function() {
return window.confirm(this.title || 'Delete this record?');
});

Q: Now that 1.4 has been released, is there a more elegant way to write the selector?


jQuery 1.4 has no new selectors that will change that expression.

I would highly suggest you give the element(s) in question an ID (if there is one) or a class (if there are several) instead as they're much faster than attribute selectors.


No, there are no new selectors, but if you find yourself doing something similar a lot you can create your own selector. Here is one with somewhat limited use:

$.expr[':'].delete_button = function(el) { 
    return $(el).is(':submit') && el.name === 'Delete' && el.value === 'Delete';
};

You could then change your line to read:

$('input:delete_button').click(function() {
    return window.confirm(this.title || 'Delete this record?');
});

Here is a more functional one, that matches the string arbitrarily:

$.expr[':'].btn = function(el, i, parts) { 
    return $(el).is(':submit') && el.name === parts[3] && el.value === parts[3];
};

It would be called like this:

$('input:btn(Delete)').click(function() {
    return window.confirm(this.title || 'Delete this record?');
});

But would also work if you used the same naming structure for other buttons:

$('input:btn(Save)').click(function() {
    return window.confirm(this.title || 'Save this record?');
});
0

精彩评论

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