Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
424 views
in Technique[技术] by (71.8m points)

php - Multiple class attributes in HTML

What happens when an element has multiple class attributes?

<div id="test" class="one two three" class="four">

I'm trying to add a class to the output of post_class(); in a WordPress plugin, but the function itself is creating the entire part class="one two three"

Is it equivalent to class="one two three four"? Or does the first or second win? Or is it undefined behaviour, in which case what do the major browsers do?

If you know the correct way of adding a class to this snippet (WordPress plugin), then that would also be appreciated!

<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What happens when an element has multiple class attributes?

When an attribute is declared multiple times for a single element (which is invalid HTML, by the way), behavior-wise the first value will override all subsequent values for the same attribute. So in this case, your element will only have the classes one two three.

This behavior is explained in the HTML5 spec, 8.2.4.35 Attribute name state, "... if there is already an attribute on the [element] with the exact same name, then this is a parse error and the new attribute must be removed..."

If you know the correct way of adding a class to this snippet (WordPress plugin), then that would also be appreciated!

Typically, if you need to add custom classes dynamically to your WordPress posts, you hook onto the post_class filter and manipulate the $classes array as necessary. Here's what it roughly looks like in my themes:

function nv_post_class( $classes ) {
    // Most recent post on the front page
    global $count;
    if ( is_home() && 1 == $count )
        $classes[] = 'latest-post';

    return $classes;
}

add_filter( 'post_class', 'nv_post_class' );

If you only need to add one or more static classes, pass them as a space-delimited string directly to post_class():

<div id="post-<?php the_ID(); ?>" <?php post_class( 'myclass1 myclass2' ); ?>>

More on this in the WordPress Codex.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...