我在wordpress中工作自定义帖子,在这个自定义帖子中,我想使用wp_attachment添加许多照片,我在这里遇到的问题是,当我点击addmore时什么都没有发生,就像如果wordpress忽略了我的jquery文件我的代码
<div class="col-sm-9">
<input type="file" name="aduploadfiles[]" id="uploadfiles2" size="35" class="form-control" />
<input type="button" id="add_more2" class="upload" value="add more photo"/>
</div>
这是我使用的javascript
var abc = 0; //Declaring and defining global increement variable
$(document).ready(function() {
//To add new input file field dynamically, on click of "Add More Files" button below function will be executed
$('#add_more2').click(function() {
$(this).before($("<div/>", {id: 'uploadfiles2'}).fadeIn('slow').append(
$("<input/>", {name: 'aduploadfiles[]', type: 'file', id: 'aduploadfiles',size:'35', class:'form-control'})
));
});
//following function will executes on change event of file input to select different file
$('body').on('change', '#file', function(){
if (this.files && this.files[0]) {
abc += 1; //increementing global variable by 1
var z = abc - 1;
var x = $(this).parent().find('#previewimg' + z).remove();
$(this).before("<div id='abcd"+ abc +"' class='abcd'><img id='previewimg" + abc + "' src=''/></div>");
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
$(this).hide();
$("#abcd"+ abc).append($("<img/>", {id: 'img', src: 'x.png', alt: 'delete'}).click(function() {
$(this).parent().parent().remove();
}));
}
});
//To preview image
function imageIsLoaded(e) {
$('#previewimg' + abc).attr('src', e.target.result);
};
$('#upload').click(function(e) {
var name = $(":file").val();
if (!name)
{
alert("First Image Must Be Selected");
e.preventDefault();
}
});
});
当我在wordpress页面中尝试时,它工作得很好,但在仪表板中,它不想工作,即使我的javascript加载
有几个问题:
1。$
不可用。使用jQuery
在WordPress中,jQuery运行在兼容模式,即$
快捷方式不可用。您可以通过在ready
方法中捕获jQuery
作为函数参数来解决这个问题,如下所示:
jQuery(document).ready(function($) {
ready
回调中的其余代码可以继续使用$
。
2。文件上传输入元素选择器错误
你在jQuery选择器中提到了错误的id:你的文件上传元素有id uploadfiles2
,而不是file
。所以改变:
$('body').on('change', '#file', function(){
:
$('body').on('change', '[name="aduploadfiles[]"]', function(){
3。重复id
值
每次当你添加一个新的按钮,你创建一个div
与uploadfiles2
的id
:但该id已经存在。在HTML中,id值必须是唯一的,否则会发生意外的事情。
动态创建的所有元素都应该有一个动态创建的(不同的)id值(或者根本没有id)