【问题标题】:How to update value of an attribute of an element, then trigger click on it? [closed]如何更新元素属性的值,然后触发点击它? [关闭]
【发布时间】:2017-11-20 04:27:19
【问题描述】:

我想使用 jQuery 来更新 type = "file" 的输入元素的属性 "accept" 的值,然后激活它的 "click" 事件。但是在“接受”的值改变之后,什么也没有发生。 这是我的代码

//html elements
<button type="button" class="abc" title="Select files from your computer" id="upload" onclick="updateExtension()"></button>
<input type="file" name="image" id="image" multiple="multiple" /> //this input field is hidden and is applied with jquery-file-upload

//jQuery function
function updateExtension(){
  $('#image').attr('accept', '.jpg, .png');
  $('#image').click();
}

【问题讨论】:

  • 尝试 $('#image').trigger('click') 而不是 $('#image').click()
  • @PrasannaVenkatesh 试过了,结果一样
  • 它按预期工作,你遇到什么问题
  • @brk 我不知道。当我点击按钮时,“接受”的值被更新,然后由于输入元素的类型是“文件”,它的点击事件将显示一个文件对话框,但在我的情况下它什么也不显示,也没有记录任何错误在控制台中。
  • 看起来不错,检查一下这个小提琴jsfiddle.net/ynfo1n0a你在控制台中看到任何错误吗?

标签: javascript jquery html jquery-file-upload


【解决方案1】:

你可以简单地使用:

$( "#image" ).trigger( "click" );

更多关于 jQuery 触发器的信息click here

【讨论】:

    【解决方案2】:

    使用这个的简单方法:--

    <!DOCTYPE html>
    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    
    <script>
    $(document).ready(function(){
        $("#click").click(function(){
                   //if update(div)content
                   $(".update_new_value").html("<h1>Enter content</h1>");
                   //if change attr value
              $("#urls_change").attr("href", "https://www.changers.com/"); 
    
        });
    });
    </script>
    </head>
    <body>
    
    <div class="update_new_value"></div>
     <p><a href="https://www.anyurls.com" id="urls_change">change urls</a></p>
    
    <button name="btn" id="click" type="button">Click Me</button>
    
    
    </body>
    </html>

    【讨论】:

      猜你喜欢
      • 2021-05-11
      • 2022-09-27
      • 1970-01-01
      • 2020-12-27
      • 1970-01-01
      • 2017-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多