我一直在试图弄清楚如何在 div 中获取所有输入元素,包括 select 和 textarea 并将它们传递给编辑器,到目前为止我想出了输入,但我只是坚持其余的。
这是到目前为止的代码
function InsertShortcode(elem) {
var shortcodeName = elem.parentElement.id;
var inputs = document.getElementById(shortcodeName).getElementsByTagName('input'), i=0, e;
var inputs_val = '[' + shortcodeName;
while(e=inputs[i++]){
if(e.id){
inputs_val += ' ' + e.id + '="' + e.value + '"';
}
}
inputs_val += ']';
window.send_to_editor(inputs_val);
}
通过这个,我能够抓取提交按钮所在的 div 中的所有输入,但我仍然不确定如何抓取 textarea 或选择输入。
问题是我必须让它动态。我会有很多“短代码”,每个都在它自己的
div
中,按钮所在的位置。但是每个人都有自己的输入,我无法控制,所以我需要全部获取它们并将值发送给编辑器。这是代码的示例。 <div class="output-shortcodes">
<?php foreach( $theme_shortcodes as $key => $name ) { ?>
<div id="<?php echo $key ?>">
<p>
<h2><?php echo $name ?></h2>
</p>
<?php $form = $key . '_form';
if(function_exists($form)) {
$form(); // this is where the input fields are dynamically created on each shortcode.
}
?>
<button class="button-primary" onclick="InsertShortcode(this)">Insert shortcode</button>
</div>
<?php } ?>
</div>
最佳答案
使用 jQuery 和 :input
伪选择器:
$('.output-shortcodes').find(':input');
就那么简单。
https://api.jquery.com/input-selector/
或者将其包装在
<form>
中,然后您可以使用:document.getElementById("outputForm").elements...
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/elements
关于javascript获取div内的所有输入,包括select和textarea,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34164035/