$(document.body).on('change','。someclass',function(){});不行

时间:2017-04-22 11:50:32

标签: javascript jquery

在我的应用程序中,我需要在将文件加载到html文件输入标记时触发JQuery函数。

下面给出的文件输入代码是参考文章http://www.jasny.net/bootstrap/javascript/#fileinput实现的。

<div class="fileinput fileinput-new" data-provides="fileinput">
    <div class="fileinput-preview thumbnail" data-trigger="fileinput" style="width: 200px; height: 150px;"></div>
    <div>
        <span class="btn btn-default btn-file">
            <span class="fileinput-new">Select image</span>
            <span class="fileinput-exists">Change</span>
            <input type="file"  class="tenderImage">
        </span>
        <a href="#" class="btn btn-default fileinput-exists" data-dismiss="fileinput">Remove</a>
    </div>
</div>

我需要在将文件加载到input元素时执行的函数。为此,我写了以下代码。

$(document).ready(function(){
    $(document.body).on('change','.tenderImage', function(){
         alert("fired");
     });
});

但是,上面的功能没有被执行。但如果我按照以下方式写同样的东西,它就会被执行。

$(document).ready(function(){
    $('.tenderImage').change(function(){
          alert("fired");
    });
});

前者不能工作的原因可能是什么?我需要以这种方式实现这个功能,因为下面的问题讨论了这个原因。

Jquery event handler not working on dynamic content

修改

根据从评论中获取的信息更改代码。信息是不使用原始的Jquery函数,而是使用我正在使用的库提供的函数。

仍然不起作用。这是JSFidle。 https://jsfiddle.net/Viraj_Gamage/2e4eochj/1/

1 个答案:

答案 0 :(得分:2)

使用您正在使用的events from the plugin(如评论中所述)

$(document.body).on("change.bs.fileinput", function() {
  alert("changed");
});

如果您需要委派活动,请使用div.fileinput(或更确切地说:div.fileinput.fileinput-exists)作为选择器

$(document.body).on("change.bs.fileinput", "div.fileinput.fileinput-exists", function() {
  alert("changed");
});

示例:

&#13;
&#13;
$(document.body).on("change.bs.fileinput", "div.fileinput.fileinput-exists", function(e) {
  alert("changed");
});
&#13;
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jasny-bootstrap/3.1.3/css/jasny-bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasny-bootstrap/3.1.3/js/jasny-bootstrap.min.js"></script>
<div class="fileinput fileinput-new" data-provides="fileinput">
    <div class="fileinput-preview thumbnail" data-trigger="fileinput" style="width: 200px; height: 150px;"></div>
    <div>
        <span class="btn btn-default btn-file">
            <span class="fileinput-new">Select image</span>
            <span class="fileinput-exists">Change</span>
            <input type="file"  class="tenderImage">
        </span>
        <a href="#" class="btn btn-default fileinput-exists" data-dismiss="fileinput">Remove</a>
    </div>
</div>
&#13;
&#13;
&#13;

fiddle