当我动态添加输入时,onfocus功能不起作用。“onfocus”事件不适用于动态附加输入
我的代码
$i=1;
<?php for($i=0;$i<=5;$i++){?>
<input type="text" onfocus="myFun(<?php echo $i?>)">
<?php}?>
我的功能是
function myFun(val){
alert(val);
}
当我动态添加输入时,onfocus功能不起作用。“onfocus”事件不适用于动态附加输入
我的代码
$i=1;
<?php for($i=0;$i<=5;$i++){?>
<input type="text" onfocus="myFun(<?php echo $i?>)">
<?php}?>
我的功能是
function myFun(val){
alert(val);
}
如果你可以使用jQuery,你可以这样做。动态添加的输入将以聚焦方式以这种方式工作。
//******************************************************************
// JAVASCRIPT
//******************************************************************
// some function to do after focus.
// takes a value variable called val
function myFun(val){
console.log(val);
}
// If you use the on method this way even if you
// add inputs after the DOM is loaded, then any
// inputs with the class name "myInput" will
// pass the focused value of the input to the myFun
// function above.
$("body").on("focus", ".myInput", function(){
myFun($(this).val());
});
//******************************************************************
// PHP
//******************************************************************
<?php
for($i=0;$i<=5;$i++){
echo "<input type='text' class='myInput' value='test value here => ".$i."'>";
}
?>
因为所有的输入是萨姆斯:(你需要添加一些
<?php
$i=1;
for($i=0;$i<=5;$i++){?>
<input name="post_name[]" id="id_<?php echo $i?>" type="text" onfocus="myFun(<?php echo $i?>)">
<?php}?>
的JavaScript:
function myFun(val){
alert(val);
}
如何名称此事与OP的问题吗? – Shiladitya
是的,你是对的,我忘记了名字 – 2017-09-15 08:00:41
我的观点是名字是如何帮助在这种情况下? – Shiladitya
非常感谢,它工作正常。 –