插入的输入字段JQuery的自定义名称 [英] Custom name for inserted input field JQuery
问题描述
在我的wordpress网站上,我正在插入输入字段并使用Ajax获取数据.
In my wordpress website i am inserting input field's and getting data with Ajax.
这是Jquery:
<script>
$(function() {
$('body').on('click', '.post-link', function() {
$('#post-cont').fadeIn();
var post_names = '';
var ajax = {};
ajax.id = $(this).attr('rel');
var ajaxurl = '<?php echo site_url() ?>/wp-admin/admin-ajax.php';
jQuery.post(ajaxurl, {
'action': 'get_img_post_and_title',
'data': ajax
}, function(response) {
if (response.success) {
if (post_names === '') {
post_names = 'aa';
} else if (post_names === 'aa') {
post_names = 'ab';
} else if (post_names === 'ab') {
post_names = 'ac';
} else {
post_names = 'ad';
}
if ($('#post-cont input').length <= 4) {
$('#post-cont').append('<div class="rows"><input name="' + post_names + '" value="' + response.data.post_id + '"> ' + response.data.post_title + ' <img src="' + response.data.post_thumb + '"/></input></div>');
}
}
});
});
});
</script>
PHP:
add_action("wp_ajax_get_img_post_and_title", "get_img_post_and_title");
add_action("wp_ajax_nopriv_get_img_post_and_title", "get_img_post_and_title");
function get_img_post_and_title(){
$return = array(
'post_id' => $_POST['data']['id'],
'post_title' => get_the_title($_POST['data']['id']),
'post_thumb' => wp_get_attachment_image_url(get_post_thumbnail_id($_POST['data']['id'])),
);
wp_send_json_success($return);
}
使用此脚本,我试图控制max number of input field to 4
,然后从aa, ab, ac, ad
分配自定义名称.
With this script i am trying to control the max number of input field to 4
and assign then custom names from aa, ab, ac, ad
.
此脚本成功添加了最多4个,但仅将aa
名称分配给所有错误的内容.
And this script add max 4 successfully but assign only aa
name to all that is wrong.
如何为所有插入的字段分配4个不同的名称?
推荐答案
请尝试以下代码捕捉:
<script>
var custom_input_names = ['aa', 'ab', 'ac', 'ad'];
$(function() {
$('body').on('click', '.post-link', function() {
$('#post-cont').fadeIn();
var post_names = '';
var ajax = {};
ajax.id = $(this).attr('rel');
var ajaxurl = '<?php echo site_url() ?>/wp-admin/admin-ajax.php';
jQuery.post(ajaxurl, {
'action': 'get_img_post_and_title',
'data': ajax
}, function(response) {
if (response.success) {
for (var i=0; i<custom_input_names.length; i++) {
if ($('#post-cont').find('input[name=' + custom_input_names[i] + ']').length < 1) {
$('#post-cont').append('<div class="rows"><input name="' + custom_input_names[i] + '" value="' + response.data.post_id + '"> ' + response.data.post_title + ' <img src="' + response.data.post_thumb + '"/></input></div>');
break;
}
}
}
});
});
});
</script>
如果希望限制大于4,则可以向custom_input_names
添加更多元素.
例如,如果您希望最大为7,则可以如下更改custom_input_names
:
You can add more elements to custom_input_names
if you want the limit more than 4.
For example, if you want maximum 7, then you can change custom_input_names
like following:
var custom_input_names = ['aa', 'ab', 'ac', 'ad', 'ae', 'af', 'ag'];
这篇关于插入的输入字段JQuery的自定义名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!