我正在尝试将带有jquery的值传递给woocommerce中的SKU输入字段,该字段是在wp-admin/edit.php?post_type=product
中单击快速编辑按钮时动态生成的,但由于某种原因未将字段值粘贴到该值。
function generateRandomString($length = 10) {
$characters = '0123456789ABCDEFGHIJKMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
function quick_edit_sku($product) {
$string = generateRandomString(); // outputs a random string correctly
?>
<script>
jQuery(document).ready(function($) {
$('.editinline').on('click', function(event) {
var sku_val = $("input[name=_sku]").val(); // checks if there is a value
var random = '<?php echo $string ?>';
if (sku_val === '') { // if SKU field is empty than apply random string. Though this doesn't work quite well, only on the second time I click quick edit it returned correct
console.log(random);
$("input[name=_sku]").val(random);
} else {
console.log('Already has value SKU value');
}
});
});
</script>
<?php }
add_filter( 'admin_footer', 'quick_edit_sku' );
答案 0 :(得分:1)
问题是js很快被触发,当你点击“Quick Edit”时,wordpress会发送一个Ajax请求来获取快速编辑选项的HTML,所以input[name=_sku]
实际上并不存在于初始状态单击。只需在添加值之前添加setTimeout
函数即可:
<script>
jQuery(document).ready(function($) {
$('.editinline').on('click', function(event) {
var sku_val = $("input[name=_sku]").val();
var random = '<?php echo $string ?>';
if (!sku_val) {
console.log(random);
setTimeout(function(){
$("input[name=_sku]").val(random)
}, 100);
} else {
console.log('Already has value SKU value');
}
});
});
</script>
此外,您的支票if (sku_val === '') { ... }
失败了。
然而,使用if (!sku_val) { ... }
会有效。
(在WP 4.1.1上测试)