jQuery的。各种项目的前缀选择器

时间:2013-02-19 09:06:28

标签: jquery prefix

如何优化这个?

$('link[href="dir/style.css"]').attr("href", "dir/style2.css");
$('link[href="../../dir/style.css"]').attr("href", "../../dir/style2.css");
jQuery('link[href="../dir/style.css"]').attr("href", "../dir/style2.css");

3 个答案:

答案 0 :(得分:1)

使用attribute ends with selectorattr的一次调用应该会这样做:

$('link[href$="style.css"]').attr('href', function(index, value) {
    return value.replace('style.css', 'style2.css');
});

JSFiddle Example

答案 1 :(得分:0)

你可以这样做:

$('link[href*="dir/style.css"]').attr('href', function(i, oldHref) {
    return oldHref.replace('dir/style.css', 'dir/style2.css');
});

使用attribute-contains选择器选择元素,然后将函数传递给.attr()的调用以返回更新的值。

答案 2 :(得分:0)

这取决于你的项目结构,但你可以做这样的事情

$('a[href*="dir/style.css"]').attr('href', function(i,href) {
       // return a version of the href that replaces "style." with "style2."
    return href.replace('style.', 'style2.');
});

在这里小提琴:http://jsfiddle.net/dT8j6/123/

相关问题