上下文
我正在尝试对此 WordPress question 建立一个答案.
我正在媒体上传厚盒窗口中生成动态复选框。它们应该用于填充文本字段,用户可以在其中复制/粘贴其值。
文本字段的最终输出是此短代码中的 include 属性 [gallery include="23,39,45"]
.
主要是,我需要帮助来构建最后一部分:复选框 -> 填充/取消填充文本字段...
<小时/>布局
动态复选框
文本字段的插入点(在控制台中显示的最后一个
<tr>
之后)要填充的文本字段,应为 include=" + CheckBoxID1 comma CheckBoxID2 comma 等 + "
实际代码
<?php
add_action( 'admin_head-media-upload-popup', 'wpse_53803_script_enqueuer' );
function wpse_53803_script_enqueuer() {
if( $_GET['tab'] == 'gallery' )
{
?>
<style>#media-upload th.order-head {width: 5%} #media-upload th.actions-head {width: 10%}</style>
<script type="text/javascript">
jQuery(document).ready( function($) {
/* Iterate through the media items */
$('.filename.new').each(function(i,e){
var id = $(this).next('.slidetoggle').find('thead').attr('id').replace(/media-head-/, '');
var filename = $('<label>Add to gallery list <input type="checkbox" name="gal-item-'+id+'" id="gal-item-'+id+'" value="" /></label>').insertBefore($(this));
filename.css('float','right').css('margin-right','40px');
filename.id = id; // PROBLEM: not sure how to do this in Javascript
// BUG: the alert is being fired twice
filename.click(function() {
alert('Handler for img id = '+filename.id+' called.');
});
});
});
</script><?php
}
}
<小时/>
缺少零件
- 创建要填充的动态文本字段。
- 解决评论中注意到的问题和错误。
- 制作
filename.click(function()
在文本字段内构建所需的字符串。
最佳答案
您可以使用类似的东西来做到这一点
$(document).on('change','input[type="checkbox"][name^="gal-item"]',function(){
var checkedIds = $('input[type="checkbox"][name^="gal-item"]:checked')
.map(function(){
return parseInt($(this).prop('name').replace(/gal-item-/,''));
}).get();
$('#shortcode').val('include="'+checkedIds.join(',')+'"');
});
您可以将 document
替换为任何您必须通过检查添加媒体标记找到的更接近的静态容器
。
并且您已经找到一个要添加输入字段的元素,添加如下
$('<span>[gallery</span><input type="text" id="shortcode" /><span>]</span>')
.appendTo(TARGETIDORCLASS);
基于此,您重写的代码将类似于
jQuery(document).ready( function($) {
//add input field
$('<span>[gallery</span><input type="text" id="shortcode" /><span>]</span>')
.appendTo(TARGETIDORCLASS);
//bind checkbox change handler
$(document).on('change','input[type="checkbox"][name^="gal-item"]',function(){
var checkedIds = $('input[type="checkbox"][name^="gal-item"]:checked').map(function(){
return parseInt($(this).prop('name').replace(/gal-item-/,''));
}).get();
$('#shortcode').val('include="'+checkedIds.join(',')+'"');
});
/* Iterate through the media items */
$('.filename.new').each(function(i,e){
var id = $(this).next('.slidetoggle')
.find('thead')
.attr('id')
.replace(/media-head-/, '');
var filename = $('<label>Add to gallery list <input type="checkbox" name="gal-item-'+id+'" id="gal-item-'+id+'" value="" /></label>')
.insertBefore($(this));
filename.css('float','right').css('margin-right','40px');
});
});
这应该有效。我很着急,无法进行太多测试,如果您发现任何错误,请检查并告诉我,我很乐意修复这些错误。
关于jquery - 使用 jQuery 根据复选框 ID 填充文本字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10907692/