0

在 jsfiddle 上有代码

我们使用的 jquery 1.4.4 目前还无法更新到较新的版本,我可以在其中让我的代码正常工作。

所以我需要在 domready 或 pageload 上,将 attr 添加到众多<a标签中。有人可以帮我找出一种方法,可以使用 javascript 和/或所需版本的 jquery。

谢谢你。

4

1 回答 1

1

您可以使用.attr(index, callback)过程轻松完成,如下所示:

$('a').attr('href', function(index, oldAttr) {
    if (oldAttr.indexOf('test') >= 0) {
        $(this)
            .removeAttr('onclick')
            .get(0)
            .setAttribute("onclick", "test");
    }
});​

演示

但是,如果您想使用,请.each()尝试如下:

$('a').each(function(index, element) {
    var el = $(element),
        hasHref = !el.attr('href'); // return true, if no href
    if( !hasHref ) {
        var href = el.attr('href'); 
        if( href.match('test').length || href.match('test-page').length ) {
         el
           .removeAttr("onclick")
           .get(0)
           .setAttribute("onclick", "test");
        }
    }
});​

演示

于 2012-09-18T15:59:33.133 回答