[英]Check previous page URL contains a string, then add class to element on the current page
[英]How to add a class to element that contains current URL
我有一個包含多個 url 的全局表,並且正在嘗試將 class 添加到與當前網站 url 匹配但卡住的表中。 任何人都可以給我一個提示?
我最接近 jQuery,它適用於文本但不適用於變量。
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var url = window.location.href;
$("tr:contains(url)").addClass('active');
});
</script>
HTML
<table id="press" class="press1">
<thead>
<tr class="row-1">
<th class="column-1">day</th>
<th class="column-2">month</th>
<th class="column-3">time</th>
<th class="column-4">place</th>
<th class="column-5">production</th>
</tr>
</thead>
<tbody class="row-hover">
<tr class="row-2">
<td class="column-1">10</td>
<td class="column-2">oktober</td>
<td class="column-3">18:00-19:00</td>
<td class="column-4">place</td>
<td class="column-5"><a href="http://link.se/production1">production name 1</a></td>
</tr>
<tr class="row-3">
<td class="column-1">11</td>
<td class="column-2">december</td>
<td class="column-3">18:00-19:00</td>
<td class="column-4">place</td>
<td class="column-5"><a href="http://link.se/production2">production name 2</a></td>
</tr>
<tr class="row-3">
<td class="column-1">22</td>
<td class="column-2">december</td>
<td class="column-3">18:00-19:00</td>
<td class="column-4">place</td>
<td class="column-5"><a href="http://link.se/production3">production name 3</a></td>
</tr>
</tbody>
</table>
:contains()
選擇器只匹配包含特定文本的元素。 要匹配元素屬性的值(例如href
),請使用Attribute Equals Selector :
屬性等於選擇器
選擇具有與某個值完全相等的指定屬性的元素。jQuery( "[attribute='value']" )
另請參閱其他 屬性選擇器:包含*=
,以^=
開頭,不等於!=
等。
在您的情況下,我們希望將 class 添加到包含具有特定href
值的<a>
的<tr>
元素。
一種方法是使用:has()
選擇器:
有選擇器
選擇至少包含一個與指定選擇器匹配的元素的元素。jQuery( ":has(selector)" )
let url = window.location.href; $(function() { $('tr:has(a[href="' + url + '"])').addClass('active'); });
.active { background-color: lightgreen; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tr><td><a href="https://example.com/">Example</a></td></tr> <tr><td><a href="https://stacksnippets.net/js">This Page</a></td></tr> <tr><td><a href="https://example.com/">Another Example</a></td></tr> </table>
另一種方法是 select 的<a>
元素,然后向上遍歷到相應的<tr>
。
let url = window.location.href; $(function() { $('a[href="' + url + '"]').closest('tr').addClass('active'); });
.active { background-color: lightgreen; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tr><td><a href="https://example.com/">Example</a></td></tr> <tr><td><a href="https://stacksnippets.net/js">This Page</a></td></tr> <tr><td><a href="https://example.com/">Another Example</a></td></tr> </table>
url
未在您的選擇器中按您的預期進行評估; 您實際上是在尋找包含文本“url”的任何表格行。
相反,請執行以下操作:
$("tr:contains(" + url + ")").addClass('active');
根據您的數據,您可能需要擔心 escaping ,但這至少應該讓您開始。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.