Prepending a dynamic 'a' tag to the 'l

2019-09-14 22:17发布

问题:

Please take a look at the code below:

<ul id="all-movies">                    
  <li class="movie">
    <img src="pic.jpg" />
  </li>
  <li class="movie featured">
    <img src="pic.jpg" />
  </li>
  <li class="movie featured">
    <img src="pic.jpg" />
  </li>
</ul>

In the code above, I would like to prepend <a href="<?php bloginfo('url'); ?>/hello"></a> to the li elements with a class of featured so that it looks like this:

<ul id="all-movies">                    
  <li class="movie">
    <img src="pic.jpg" />
  </li>
  <li class="movie featured">
    <a href="<?php bloginfo('url'); ?>/hello"></a>
    <img src="pic.jpg" />
  </li>
  <li class="movie featured">
    <a href="<?php bloginfo('url'); ?>/hello"></a>
    <img src="pic.jpg" />
  </li>
</ul>

And <?php bloginfo('url'); ?> will be replaced with my site.

How can I get this to work? I have tried something like the following but it didn't work:

$("#all-movies li").hasClass('featured').prepend('<a href="<?php bloginfo('url'); ?>/hello"></a>');

Note: The featured class is being added dynamically.

-edit- This is the code I'm using to add the featured class dynamically:

function wpse80098_filter_post_class( $classes ) {
    global $post;
    if ( 'yes' == get_post_meta( $post->ID, '_jsFeaturedPost', true ) ) {
        $classes[] = 'featured';
    }
    return $classes;
}
add_filter( 'post_class', 'wpse80098_filter_post_class' );

回答1:

hasClass returns a boolean value which doesn't have prepend method, you can use class selector.

$("#all-movies li.featured").prepend('<a href="<?php bloginfo("url"); ?>/hello"></a>');

or:

$("#all-movies li").filter('.featured').prepend('<a href="<?php bloginfo("url"); ?>/hello"></a>');


回答2:

<script>
$(document).ready(function(){
    var yourURL = "<?php bloginfo('url'); ?>/hello";
    $("#all-movies li.featured").prepend('<a href="'+yourURL+'"></a>');
});
</script>


回答3:

You can try out with .find() function:

var url = "<?php bloginfo('url'); ?>/hello";
$('ul#all-movies').find('li.featured').prepend("<a href='"+url+"'></a>");


回答4:

$('li.featured').each(function(){
   $(this).prepend('<a href="<?php bloginfo("url"); ?>/hello"></a>');
});


回答5:

Have you tried:

$("#all-movies li.featured").prepend('<a href="<?php bloginfo('url'); ?>/hello"></a>');

Thats assuming the <?php ?> stuff is actually processed on your server and doesn't make its way to the client.