更改输入的类型

Changing type of an input

本文关键字:类型 输入      更新时间:2023-09-26

我想在点击按钮时更改输入的类型,但它不起作用。我试过这个:

$('.addPhoto').click(function(){
 $(this).siblings('.auto_image').prop("type", "file");
});

它一点作用都没有。我在谷歌上搜索后发现:使用jQuery 更改输入字段的类型

它说可以用直接的DOM来实现,但是我如何用DOM来选择同级的类呢?

您可以一起替换元素,但我认为您不能只更改类型属性,请参阅我的示例。

$('.addPhoto').on("click",function(){
    $(this).off("click").replaceWith("<input type='file' class='addPhoto'/>");
});

$('.addPhoto').one("click",function(){
    $(this).replaceWith("<input type='file' class='addPhoto'/>");
});

http://jsfiddle.net/ECzP4/

这是replaceWith()的jQuery文档http://api.jquery.com/replaceWith/

要获得dom对象,只需从jQuery集合中获取第一项:

var domObject = $(this).siblings('.auto_image')[0]

虽然它似乎不能从text变为file-http://jsfiddle.net/7HTgA/

因此,我建议有两个输入,并根据需要显示/隐藏它们,而不是试图更改单个输入的类型。

将其所有同级与类型为file的auto_image类相加。

$(this).siblings('.auto_image').attr('type','file')