gpt4 book ai didi

javascript - 动态添加和删除帖子标题

转载 作者:行者123 更新时间:2023-12-01 04:00:17 26 4
gpt4 key购买 nike

在我的 WordPress 网站中,我创建了一个 Ajax 搜索并搜索 post_title。代码在这里...

函数和脚本:

<?php
add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() {
?>
<script type="text/javascript">
function fetch(){
jQuery.ajax({
url: ajaxwpse.ajaxurl,
type: 'post',
data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
success: function(data) {
jQuery('#datafetch').html( data );
}
});
}
</script>
<?php
}
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){

if ( esc_attr( $_POST['keyword'] ) == null ) { die(); }
$the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => array('mobile','tablet') ) );
if( $the_query->have_posts() ) :
while( $the_query->have_posts() ): $the_query->the_post(); ?>

<div>
<button class="post-link" rel="<?php the_ID(); ?>"> ADD </button>
<li><a href="#" id="<?php the_ID(); ?>"><?php the_title();?></a></li>
</div>

<?php endwhile;
wp_reset_postdata();
endif;
die();
}

使用 Ajax 成功搜索后,现在我需要动态地将 post_title 从搜索添加到 div id="post-container"

HTML

<input type="text" name="keyword" id="keyword" onkeyup="fetch()" placeholder="Search to add"></input>

<div id="datafetch"></div> // successfuly ajax Search Result Here

<div id="post-container"> </div> // Trying to add post title here

我在搜索结果中创建一个 ADD 按钮,将 post_title 添加到 div 中。

如何动态地将 post_title 从搜索字段添加到带按钮的 div 中?

最佳答案

您必须将点击事件附加到按钮,以获取 post_title 并将其附加到 div :

$(function(){
$('body').on('click', '.post-link', function(){
var post_title = $(this).closest('div').find('a').text();
$('#post-container').append( post_title );
});
});

希望这有帮助。

$(function(){
$('body').on('click', '.post-link', function(){
var post_title = $(this).closest('div').find('a').text();

if( $('#post-container p').length < 4 )
$('#post-container').append( '<p>' + post_title + ' ------ <a href="#" class="remove-title">REMOVE</a></p>' );
else
alert('You could add max 4 titles');
});

$('body').on('click', '.remove-title', function(){
$(this).closest('p').remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>
<button class="post-link"> ADD </button>
<li>
<a href="#">The title 1 HERE</a>
</li>
</div>

<div>
<button class="post-link"> ADD </button>
<li>
<a href="#">The title 2 HERE</a>
</li>
</div>

<div>
<button class="post-link"> ADD </button>
<li>
<a href="#">The title 3 HERE</a>
</li>
</div>

<hr>
<div id="post-container"> </div>

关于javascript - 动态添加和删除帖子标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42249506/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com