Php 如何通过jQuery选择动态生成的Id?
我有PHP动态生成的Id:Php 如何通过jQuery选择动态生成的Id?,php,jquery,select,dynamic,Php,Jquery,Select,Dynamic,我有PHP动态生成的Id: <input type="submit" class="btn btn-primary register" id="wp-submit<?php $template->the_instance(); ?>" value="Register" /> 如果在生成的页面中以内联的标记输出js代码,那么只需在PHP中添加一个echo。(这不能作为外部JS文件的一部分使用) 。。。页面内容 $('#wp submit').val(); 注意-
<input type="submit" class="btn btn-primary register" id="wp-submit<?php $template->the_instance(); ?>" value="Register" />
如果在生成的页面中以内联的
标记输出js代码,那么只需在PHP中添加一个echo
。(这不能作为外部JS文件的一部分使用)
。。。页面内容
$('#wp submit').val();
注意-您还需要对ID属性执行相同的操作,以获得要显示的值
id="wp-submit<?php echo $template->the_instance(); ?>"
id=“wp提交”
您不需要id。使用$('.register')
编辑好的,您可以通过$('input[type=submit].register')获得它。
因为混合使用服务器端语言和客户端语言从来都不是一个好主意,我猜Wordpress的名字是wp submit
和变量$template->the_instance()
在Wordpress中,正确的方法是在包含脚本时对其进行本地化,并以这种方式将值传递给脚本
<?php
wp_register_script( 'my_script', 'path/to/myscript.js', array( 'jquery' ));
$values_to_pass = array( 'instance' => $template->the_instance() );
wp_localize_script( 'my_script', 'object_name', $values_to_pass );
// The script can be enqueued now or later.
wp_enqueue_script( 'my_script' );
?>
您应该设置一个要选择的类,如$('.wp submit register').val()
。如果ID是动态的,那么我不理解您为什么要将事件绑定到具有该特定ID的特定元素。如上所述,您应该改为使用类。如果是这样,Wordpress,有一种特殊的方法可以将值传递给脚本。如果这是唯一一个使用动态id的按钮?您可以使用$('input[id^=“wp submit”]”)。val()
,这将选择以关键字“wp submit”开头的任何id。您在该页面上有多个提交按钮吗?您如何知道$template->the_instance()
尚未回显值?@ChristianVarga很好。我对此做了一个假设,甚至没有意识到。感谢您指出这一点。一个类被设计用于几个不同的元素。假设他在多个字段中使用.register
。您的解决方案仍然适用吗?@JamesMcDonnell,是的,它将按操作要求选择此输入,提交时
您可以执行任何验证:id、类型等。但如果您有十个元素具有相同的类,它将选择所有十个元素elements@adeneo当然,将提交事件绑定到页面上的所有“注册”按钮是显而易见的(即使它们是多重的,尽管我认为这是唯一的)然后检查
id="wp-submit<?php echo $template->the_instance(); ?>"
<?php
wp_register_script( 'my_script', 'path/to/myscript.js', array( 'jquery' ));
$values_to_pass = array( 'instance' => $template->the_instance() );
wp_localize_script( 'my_script', 'object_name', $values_to_pass );
// The script can be enqueued now or later.
wp_enqueue_script( 'my_script' );
?>
$('#wp-submit' + object_name.instance ).val();