jQuery .change()在输入类型=“文件”时失败

时间:2014-03-11 00:44:18

标签: jquery knockout.js

这不起作用

<input type="file" id="foo" />
...
$("#foo").change(function() { alert('bing') });

但是这样做

<input type="file" id="foo" onchange="alert('bing')" />

元素ID值是唯一的。

我是否错误地使用了jQuery,或者输入type =“file”是否存在问题?

我注意到敲除绑定似乎不适用于输入type =“file”,迫使我显式绑定更改处理程序以更新视图模型。 (由于过早阅读Arun关于绑定的评论,我尝试让KO数据绑定用于更改事件。工作,这很方便但意外,因为原始问题是KO无法数据绑定值。)

<!-- in view -->
<input type="file" id="inputFile" data-bind="event: {change: choseFile}" />
<button class="button" data-bind="click: chooseFile">Select the file</button>
<textarea readonly="readonly" data-bind="text: newUpload.fileName" />

//in view model
return {
  history: history,
  newUpload: newUpload,
  choseFile: function () { newUpload.fileName($("#inputFile").val()); },
  chooseFile: function () { $("#inputFile").click(); },
};

正如您从示例中看到的那样,我已经解决了input type="file"无法通过完全隐藏它并使用代理小部件来响应CSS的旧难题。

Restyled file input

特别是它可以更好地处理长路径。

1 个答案:

答案 0 :(得分:-2)

您可以使用$(“#foo”)查找是否没有多个元素。

请参阅下文。这是我当地的工作。

$("#foo").on('change', function(){

    alert('we change the file');

})

也许这是JQ问题