當我動態添加輸入時,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
非常感謝,它工作正常。 –