Jquery:选择元素A(如果存在)的惯用方法,否则元素B?

时间:2010-11-18 00:14:21

标签: jquery jquery-selectors greasemonkey

我正在用JQuery编写GreaseMonkey脚本 有时,我想修改的网站会在TD中显示信息,因此:

<center><table><tr><td>
Something interesting here.</td></tr>....</table></center>

有时它会在同一个表结构中的P标签(或几个)中显示内容,因此:

<center><table><tr><td>
<p>Other text about the same interesting thing.
<p>and maybe some more stuff too.</td></tr>...</table></center>

现在我正在做两个不同的选择器来选择<p><td>,但我想知道是否有一个很好的方法来选择只有P标签,如果它存在和否则在单个Jquery选择器中的TD,因为我想要追加的内容在两种情况下都是相同的。

(如果我只是附加到TD,无论我的添加位置是否根据P标签的存在/不存在而改变,所以我要考虑放置的一致性。)

4 个答案:

答案 0 :(得分:1)

在单个jQuery语句中不可能,但你可以这样做:

var $elem = $('p').length > 0 ? $('p') : $('table');

$elem.append(...);

答案 1 :(得分:1)

我会使用.map(或.each):

$("center > table > tbody > tr > td").map(function() {
    if($(this).find("p").length) {
        $(this).find("p").css("border", "1px solid red");
    } else {
        $(this).css("border", "1px solid green");
    } 
});

演示:http://jsfiddle.net/tBWhH/3/

答案 2 :(得分:1)

是的,你可以通过扩展jQuery来实现这一点。

将它放在GM文件的顶部附近:

$.fn.substituteIfPresent = function (tagName)
{
    return this.map (function ()
    {
        var childArray = $(this).children (tagName);

        if (childArray.length)
            return childArray[0];
        else
            return this;
    });
}


然后你可以用:

获得所需的元素
X = $("center > table > tbody > tr > td").substituteIfPresent ('p');

//-- Note that X is a standard jQuery object, the following works:
X.css ('border', '1px solid green');


此版本的substituteIfPresent()仅返回第一个p标记(如果存在)。

答案 3 :(得分:0)

只有一个选择器操作的好方法是:

var $el = (function(){
    var $td = $('td'), // you probably want a more precise selector here
        $p = $td.find('p:last');

    return $p.length ? $p : $td;
})();

这会将$el设置为最后一个p元素(如果存在),否则设置为td元素。请注意,如果您的网页上有多个td元素,则会产生意外结果,因此您应使用比$('td')更精确的选择器。

自动执行功能的原因是避免使用额外的变量污染范围。

相关问题