如何在输入中定义onChange函数--jQuery

时间:2017-10-31 05:15:17

标签: javascript jquery html

我想动态创建输入。每个输入都有9999_99_99函数和变量。

我的所有代码:

onChange

但我的输入在更改时收到此错误消息:

var distinct_inputs = 0;
$('.icon1').click( function(){
  distinct_inputs = distinct_inputs + 1 ;
  $('#insert-file').append('<ul class="ul list-inline"><li style="width:90%"><input onchange="changePath('+distinct_inputs+')" type="file" class="base'+distinct_inputs+' form-control form-input form-style-base"><input  type="text" class="fake'+distinct_inputs+' form-control form-input form-style-fake" readonly placeholder="choose your file"><span class="glyphicon glyphicon-open input-place"></span></li><li class="icon fa fa-minus"></li></ul>');
});

function changePath(distinct_inputs) {
  console.log(distinct_inputs);
}

2 个答案:

答案 0 :(得分:0)

修改changePath功能,如下面的代码所示。它会工作。

var distinct_inputs = 0;
    $('.icon1').click( function(){
        distinct_inputs = distinct_inputs + 1 ;
        $('#insert-file').append('<ul class="ul list-inline"><li style="width:90%"><input onchange="changePath('+distinct_inputs+')" type="file" class="base'+distinct_inputs+' form-control form-input form-style-base"><input  type="text" class="fake'+distinct_inputs+' form-control form-input form-style-fake" readonly placeholder="choose your file"><span class="glyphicon glyphicon-open input-place"></span></li><li class="icon fa fa-minus"></li></ul>');
    });

changePath = function(distinct_inputs)
    {
        console.log(distinct_inputs);
    }

答案 1 :(得分:0)

实际上,您必须在Document ready之外声明更改路径。

看看它是如何工作的......:)

&#13;
&#13;
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>

    function changePath(distinct_inputs)
    {
        console.log(distinct_inputs);
    }
    
     
$(document).ready(function(){

     
var distinct_inputs = 0;
    $('.icon1').click( function(){
        distinct_inputs = distinct_inputs + 1 ;
        $('#insert-file').append('<ul class="ul list-inline"><li style="width:90%"><input onchange="changePath('+distinct_inputs+')" type="file" class="base'+distinct_inputs+' form-control form-input form-style-base"><input  type="text" class="fake'+distinct_inputs+' form-control form-input form-style-fake" readonly placeholder="choose your file"><span class="glyphicon glyphicon-open input-place"></span></li><li class="icon fa fa-minus"></li></ul>');
    });

});
</script>
</head>
<body>
<div id="insert-file" ></div>
<button type="button" class="icon1">CLick here</button>

</body>
</html>
&#13;
&#13;
&#13;