如何获取 class 属性值的一部分?
How can I get a part of the value of class attribute?
这是我的 HTML 结构:
<tr>
<td class="option_name_twitter">Something</td>
<td class="option_loading">
<img src="img/checked_successfully.png">
</td>
</tr>
<tr>
<td class="option_name_instagram">Something else</td>
<td class="option_loading">
<img src="img/checked_successfully.png">
</td>
</tr>
这是我的代码:
$(document).on('click', "img[src$='checked_successfully.png']", function () {
var name = $(this).closest('td.option_loading').sibilings('td.^option_name_').attr('class');
})
我正在尝试获取以 option_name_
开头的元素的类名值的最后一部分。因此预期结果是 twitter
或 instagram
。我该怎么做?
您可以通过从同级 td
获取 class
,使用 _
将其拆分为一个数组,然后 pop()
从最后一个元素到获得你需要的价值。像这样:
$(document).on('click', "img[src$='checked_successfully.png']", function() {
var name = $(this).closest('td.option_loading').prev('td').attr('class');
var site = name.split('_').pop();
console.log(site);
})
img {
border: 1px solid red;
width: 30px;
height: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td class="option_name_twitter">Something</td>
<td class="option_loading">
<img src="img/checked_successfully.png">
</td>
</tr>
<tr>
<td class="option_name_instagram">Something else</td>
<td class="option_loading">
<img src="img/checked_successfully.png">
</td>
</tr>
</table>
但是您应该注意,以这种方式使用 class
字符串并不理想,因为它很容易损坏。在属性末尾添加另一个 class 将破坏此代码。更好的方法是将您需要的值存储在其自己的数据属性中 - 假设您有权编辑 HTML.
这是我的 HTML 结构:
<tr>
<td class="option_name_twitter">Something</td>
<td class="option_loading">
<img src="img/checked_successfully.png">
</td>
</tr>
<tr>
<td class="option_name_instagram">Something else</td>
<td class="option_loading">
<img src="img/checked_successfully.png">
</td>
</tr>
这是我的代码:
$(document).on('click', "img[src$='checked_successfully.png']", function () {
var name = $(this).closest('td.option_loading').sibilings('td.^option_name_').attr('class');
})
我正在尝试获取以 option_name_
开头的元素的类名值的最后一部分。因此预期结果是 twitter
或 instagram
。我该怎么做?
您可以通过从同级 td
获取 class
,使用 _
将其拆分为一个数组,然后 pop()
从最后一个元素到获得你需要的价值。像这样:
$(document).on('click', "img[src$='checked_successfully.png']", function() {
var name = $(this).closest('td.option_loading').prev('td').attr('class');
var site = name.split('_').pop();
console.log(site);
})
img {
border: 1px solid red;
width: 30px;
height: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td class="option_name_twitter">Something</td>
<td class="option_loading">
<img src="img/checked_successfully.png">
</td>
</tr>
<tr>
<td class="option_name_instagram">Something else</td>
<td class="option_loading">
<img src="img/checked_successfully.png">
</td>
</tr>
</table>
但是您应该注意,以这种方式使用 class
字符串并不理想,因为它很容易损坏。在属性末尾添加另一个 class 将破坏此代码。更好的方法是将您需要的值存储在其自己的数据属性中 - 假设您有权编辑 HTML.