我用的是两个div。在第一个div中,所有用户都显示在一个页面上,带有"ADD“Button选项。通过添加用户,可以使用jQuery将用户添加到第二个div。但我想确保他们不会被加两次。我想要实现一个条件来检查一个用户是否已经被添加,那么它不应该被添加或者按钮应该被禁用。我正在编写下面的代码,并在wordpress中使用,但问题与jquery有关-
<?php
/*
Template Name: Users
*/
?>
<style>
.container{
width: 800px;
}
.left{
float:left;
width: 300px;
background: ##66CDAA;
border-right: thick-solid #fff;
}
.right{
overflow: hidden;
width: 500px;
background: powderblue;
}
</style>
<?php
get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<div class="container">
<div class="left" id="xyz">
<table>
<tr>
<th>Name</th>
<th>Gravatar Image</th>
<th>Add to Div</th>
</tr>
<?php
$sql ="SELECT * FROM wp_users";
$results = $wpdb->get_results($sql) or die(mysql_error());
foreach( $results as $result ){ ?>
<tr>
<td id="<?php echo $result->ID; ?>">
<?php echo $result->display_name; ?>
</td>
<td>
<?php echo get_avatar( $result->user_email, 42); ?>
</td>
<td>
<input type="button" class="submit" data-id="<?php echo $result->ID; ?>" data-name="<?php echo $result->display_name; ?>" data-image="<?php echo get_avatar_url($result->user_email); ?>" value="ADD"><p style="display:none;">Added</p>
</td>
</tr>
<?php
}
?>
</table>
</div>
<div class="right">
<p>Added Users</p>
<table class="table">
<tr>
<th>Name<th>
<th>Image</th>
</tr>
</table>
</div>
</div>
</main>
</div>
<?php get_footer(); ?>在我的ajax.js文件中,我将用户添加到第二个div,还有一个取消按钮要取消,但是在从第二个div取消用户之后,我们应该再次能够将用户添加到第二个div。
(function($) {
$(document).ready(function() {
$(".submit").on("click", function(e){
e.preventDefault();
var id = $(this).data('id');
var name = $(this).data('name');
var image = $(this).data('image');
//Here I want to check the condition that if a user is already added then it should not be added.
$('.table').append('<tr id=" ' + id+ ' "><td>' + name + '</td><br><td><img src=" ' + image + ' "></td><td><input type="button" value="Cancel" class="cancel"></td></tr>');
})
})
})(jQuery);因此,我的问题是,如何确保如果用户已经添加,那么它不应该再添加。为了这个,我怎么能检查这个。如果添加的用户被取消,则cancel按钮disappers和add按钮出现在第一个div中。如果现在有用户,我如何隐藏表。在我的案子里,我试过了,但不起作用。
编辑:在functions.php中,我使用了以下代码将队列登记到ajax.js文件。
<?php
function umar_scripts(){
wp_enqueue_script( 'main_ajax', get_template_directory_uri() . '/js/ajax.js', array('jquery'), '', true);
}
add_action( 'wp_enqueue_scripts', 'umar_scripts' );发布于 2017-06-15 07:26:24
下面是如何检查用户是否存在的方法:
if($('.table td#' + id).length) { // user exists }
else { // user doesn't exist }发布于 2017-06-15 07:00:30
假设要向表中的每个用户行添加uniqe id,则可以在表中添加带有该id的行是否存在。使用以下代码:
(function($) {
$(document).ready(function() {
$(".submit").on("click", function(e) {
e.preventDefault();
var id = $(this).data('id');
var name = $(this).data('name');
var image = $(this).data('image');
if ($('table').find('#' + id).length <= 0) {
{
$('.table').append('<tr id=" ' + id + ' "><td>' + name + '</td><br><td><img src=" ' + image + ' "></td><td><input type="button" value="Cancel" class="cancel"></td></tr>');
}
})
})
})(jQuery);https://stackoverflow.com/questions/44560676
复制相似问题