removeButton.click(function () {
$(this).parent().remove();
renameDivs();
});
...
function renameDivs() {
$('#image_upload div').each(function (k, v) {
$(this).attr('id', 'upload-image-set-' + (k + 1));
});
}
题
I've been playing about with some code for what seems like ages, I've now finally got it to work but there are 2 issues with it as far as I can work out.
Firstly, If you add multiple forms, it increments up i.e. 1, 2, 3 etc so if I create 3 forms and delete form 2 i'm left with forms 1 and 3, if I then go to add another form it will duplicate form 3 again then add 4, 5, 6 etc.
The way I would like it to work is, if you delete form 2, form 3 will replace all the 3's in the attributes and replace them with 2 effectively replacing form 2.
Secondly, Once I refresh the page, the forms are deleted, I would like it so that if the forms have a value to display.
Here's a fiddle: http://jsfiddle.net/33Ks6/
Here's the jquery:
// Add extra upload bars
$("#add").click(function() {
var intId = $("#image_upload div").length + 1;
var fieldWrapper = $("<div id=\"upload-image-set-" + intId + "\"/>");
var fName = $("<input type=\"text\" id=\"show_upload_image_link_" + intId + " size=\"36\" name=\"kandibox_theme_hero_options[show_upload_image_link_" + intId + "]\" value=\" <?php echo $hero_options['show_upload_image_link_1']; ?> \" />");
var mediaButton = $(" <input id=\"show_upload_image_link_" + intId + "_button\" class=\"button upload_images\" type=\"button\" value=\"Upload Image\" />");
// Media Upload Button 1
var custom_uploader;
mediaButton.click(function(e) {
e.preventDefault();
//If the uploader object has already been created, reopen the dialog
if (custom_uploader) {
custom_uploader.open();
return;
}
//Extend the wp.media object
custom_uploader = wp.media.frames.file_frame = wp.media({
title: 'Choose Image',
button: {
text: 'Choose Image'
},
multiple: false
});
//When a file is selected, grab the URL and set it as the text field's value
custom_uploader.on('select', function() {
attachment = custom_uploader.state().get('selection').first().toJSON();
fName.val(attachment.url);
});
//Open the uploader dialog
custom_uploader.open();
});
var removeButton = $(" <input type=\"button\" class=\"remove\" value=\"-\" />");
removeButton.click(function() {
$(this).parent().remove();
});
fieldWrapper.append(fName);
fieldWrapper.append(mediaButton);
fieldWrapper.append(removeButton);
$("#image_upload").append(fieldWrapper);
});
解决方案
removeButton.click(function () {
$(this).parent().remove();
renameDivs();
});
...
function renameDivs() {
$('#image_upload div').each(function (k, v) {
$(this).attr('id', 'upload-image-set-' + (k + 1));
});
}