2015-10-06 21 views
1

我有一個線如何更改選擇器:包含完全匹配一個?

$('#custom-table tr > td:nth-child(1):contains('+val+')').closest('tr').show();

,想找到一種方法,具有相同或精確匹配,而不是包含。

+1

您可以創建一個代碼片段? –

+0

你能否提供相關的html? –

+0

[jsfiddle鏈接](http://jsfiddle.net/zaga/u372rfyd/5) – user2260571

回答

1

您可以使用filter()text()

var val = 'abc'; 
 
$('#custom-table tr > td:nth-child(1)').filter(function() { 
 
    return $.trim($(this).text()) == val; 
 
    // get text content using text() and compare 
 
    // and use $.trim() for removing whitespace from the beginning and end of a string. 
 
}).closest('tr').show();
#custom-table tr { 
 
    display: none; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<table id="custom-table"> 
 
    <tr> 
 
    <td>abc</td> 
 
    <td>absc</td> 
 
    </tr> 
 
    <tr> 
 
    <td>abcd</td> 
 
    <td>abcd</td> 
 
    </tr> 
 
    <tr> 
 
    <td>abc</td> 
 
    <td>absc</td> 
 
    </tr> 
 
    <tr> 
 
    <td>abcd</td> 
 
    <td>abcd</td> 
 
    </tr> 
 
</table>

更新:對於完全相同的行爲

var val = 'abc'; 
 
$('#custom-table tr > td:nth-child(1)').filter(function() { 
 
    return $(this).text().indexOf(val) != -1; 
 
    // get text content using text() and compare 
 
    // and use indexOf() for checking string contains the value. 
 
}).closest('tr').show();
#custom-table tr { 
 
    display: none; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<table id="custom-table"> 
 
    <tr> 
 
    <td>abc</td> 
 
    <td>absc</td> 
 
    </tr> 
 
    <tr> 
 
    <td>abcd</td> 
 
    <td>abcd</td> 
 
    </tr> 
 
    <tr> 
 
    <td>abc</td> 
 
    <td>absc</td> 
 
    </tr> 
 
    <tr> 
 
    <td>abcd</td> 
 
    <td>abcd</td> 
 
    </tr> 
 
</table>

+0

試圖添加此功能沿selectize.js,但它不適用於我。這裏是[jsFiddle鏈接](http://jsfiddle.net/zaga/u372rfyd/5/) 我嘗試使選定的xAB只返回AB行,而不是ABB。 – user2260571

+0

在這種情況下,您需要使用indexof .....以上方法只適用於完全匹配......我將更新答案.. –

0
$('#custom-table tr > td:nth-child(1)').find("*").filter(function() { 
    return $(this).text() === val; 
}).closest('tr').show(); 
相關問題