简体   繁体   English

如何获得class属性值的一部分?

[英]How can I get a part of the value of class attribute?

Here is my HTML structure: 这是我的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>

And here is my code: 这是我的代码:

$(document).on('click', "img[src$='checked_successfully.png']", function () {
    var name = $(this).closest('td.option_loading').sibilings('td.^option_name_').attr('class');
})

I'm trying to get the last part of the classname's value of an element that starts with option_name_ . 我正在尝试获取以option_name_开头的元素的classname值的最后一部分。 So the expected result is either twitter or instagram . 所以预期的结果是twitterinstagram How can I do that? 我怎样才能做到这一点?

You can achieve this by getting the class from the sibling td , splitting it in to an array using _ , then pop() off the last element to get the value you need. 您可以通过从兄弟td获取class ,使用_将其拆分为数组,然后从最后一个元素的pop()中获取所需的值来实现此目的。 Something like this: 像这样的东西:

 $(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> 

You should however note that using the class string in this way is not ideal, as it's very easily broken. 但是你应该注意到以这种方式使用class字符串并不理想,因为它很容易被破坏。 Adding another class at the end of the attribute will break this code. 在属性末尾添加另一个类将破坏此代码。 A much better approach would be to store the value you need in its own data attribute - assuming you have access to edit the HTML. 一种更好的方法是将所需的值存储在自己的数据属性中 - 假设您有权编辑HTML。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM