简体   繁体   中英

How can I make this whole div clickable?

In the following PHP code for my Wordpress site, I grab the title and lede of certain child pages and display as line items in an unordered list. I've put each LI in a div.

I've used CSS to make the div change colors in its hover state and I'd like to make the entire div clickable, including its empty background.

Problem is, only the text inside becomes clickable. The background of the div does not. I want the whole div (including its empty background) to be clickable.

I know that in regular html, making an entire div clickable is easy: simply surround it with link ("a href" and "/a") tags.

That doesn't seem to work here -- only the text within becomes clickable. Is there a way to make the whole div (including its empty background) clickable? Here's the code. Thank you!

/* Get the children of the services page */
                $args = array(
        'post_type' => 'page',
        'post_parent' => $services_id
    );
    $services_query = new WP_Query( $args );

// Grab the title and lede and display them in an unordered list
     if ( $services_query->have_posts() ) {
        echo '<ul class="services-list">';
        while ( $services_query->have_posts() ) {
            $services_query->the_post();
            echo '<a href="' . get_permalink() . '" title="' . get_the_title() . '">';

            //Shouldn't this whole div be clickable? Note the link tag echoed above...
            echo '<div>'; 
            echo '<li class="clear">';
            echo '<h3 class="services-title">' . get_the_title() . '</h3>';
            echo '<div class="services-lede">';
            the_content();
            echo '</div>';
            echo '</li>';
            echo '</div>'; //end of clickable div
            echo '</a>'; //closed anchor tag
        }
        echo '</ul>';
    } 

If you want to make the DIV clickable you can use the onclick attribute of it.

Here is a plain html to do that:

 <html> <body> <div style="background: #c0c0c0" onclick="javascript:alert('bla');"> this is a clickable DIV </div> <div style="background: #e0e0e0"> this is not a clickable DIV </div> </body> </html> 

For your case it would be:

echo '<div onclick="document.location=\'' . get_permalink() . '\'">'; 

The only content allowed in 'ul' tag is 'li' tags. More on this here

So, the right order in the while loop is li -> a -> div.

Use jquery or javascript and ajax (in case you need to send data or receive)

$("div").on("click", function(){ //use ajax to send data to server };
//javascript
var div = document.getElementsByTagName("div");
div.onclick = function() { //ajax };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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