In jquery: Use attr(“class”) value as a selector?

2019-09-03 14:07发布

问题:

I have fields with multiple classes. I want to use one of those classes as a selector, how do I do this?

generic example:

<input id="from"/><div class="error from">errormessage</div>
<input id="to"/>
<div><input id="when" /></div><div class="error when">errormessage</div>

Because ther is a div.error with the class from, I want to add a certain class to input#from and the same goes for the input called when. Note that "when" is wrapped in a div. Several variations like this are necessary for the page. Therefore, tree-traversal is not a suitable solution.

回答1:

For updated question:

I think this is what you're after, since the element since to be a previous sibling or contained in one:

$(".error").prev().find("input").andSelf().filter("input").addClass("test");

You can test it out here.


For previous question: Use the .class selector, like this:

$(".myCass")

You can also select elements that only have multiple classes by chaining them, for example:

$(".myCass.myClass2.myClass3")

Would only select elements that had all 3 classes.



回答2:

jQuery selectors are nothing but strings, HTML attributes are nothing but strings and regular JavaScript has string operators and functions.

Here's a little (and meaningless) code snippet that puts these ideas together:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css"><!--
--></style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript"><!--
jQuery(function($){
    $("div").css({border: "1px solid black"}).each(function(){
        var classes = this.className.split(/\s+/);
        for(var i=0, len=classes.length; i<len; i++){
            $("." + classes[i]).append("<p>I have class " + classes[i] + "</p>");
        }
    });
});
//--></script>
</head>
<body>


<div class="foo bar dot">foo bar dot</div>
<div class="bar dot">bar dot</div>
<div class="dot">dot</div>


</body>
</html>

It's nice as a proof of concept, but you should double-check that your design is the simplest one.