javascript - 触发 iframe 内 textarea 的 'change' 事件

标签 javascript jquery events iframe textarea

我有一个页面 (index.htm),其中包含来自同一域的 iframe (iframe.htm)。

在 iframe 中有一个 textarea 元素处理它的 'change' 事件。

主页上有一个 jquery 代码,它使用 val() 更改文本区域的内容。然后我尝试触发调用 change() 函数的“change”事件。

但是,这是行不通的。值更改,但“更改”事件不起作用。如果 textarea 不在 iframe 内,这将按预期工作。

问题如何在 iframe 内的元素上强制触发事件?

iframe.htm:

<html>
<head>
    <script src="jquery.js" type="text/javascript"></script>
    <script>
    $(document).ready(function () {
        $("textarea").bind("change", function () {
            alert("changed"); });
    });
    </script>
</head>
<body>
    <textarea id="txt"></textarea>
</body>
</html>

index.htm:

<html>
<head>
<script src="jquery.js" type="text/javascript"></script>
<script>
    $(document).ready(function () {
        $("#btn").bind("click", function () {
            var frame = document.getElementById("frame");
            var txt = frame.contentDocument.getElementById("txt");
            $(txt).val("hello").change();
        });
    });
</script>
</head>
<body>
    <iframe id="frame" src="iframe.htm"></iframe>
    <button id="btn">Fire change</button>
</body>
</html>

最佳答案

试试这个:

    $iframe = $('#iframe').contents().find('#txt');

    $iframe.on('change',function(){
      var val = $(this).val();
      console.log(val);
    });

   $('#btn').click(function(){
      $iframe.trigger('change');
   });

关于javascript - 触发 iframe 内 textarea 的 'change' 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21933867/

相关文章:

javascript - jQuery - 2 级 slider 通过单击返回到 1 级

jquery - offset().top 是否应该改变

javascript - 异步 json javascript 查询失败,仅在 IE 上使用 unicode 字符

c# - FileSystemWatcher 未调用更改事件

java - 如何简单地用Java发送事件?

javascript - 在鼠标事件之间传递数据

javascript - 禁用选择 jQuery Datepicker 字段?

javascript - 在 Django 中发送字符串元素列表

javascript - 是否可以将 jQuery 对象作为构造函数参数传递给 typescript 对象?

php - 获取实际 URL,此案例的最佳实践