2010-05-17 43 views
0

如何使用jQuery而不是onchange事件重写此内容?将内联javascript重写为jQuery

<input name="PasswordName" type="password" id="passwordID"> 
<p> 
<input type="checkbox" onchange="document.getElementById('passwordID').type = this.checked ? 'text' : 'password'"> Show Password 
</p> 
+1

我相信这不会在IE浏览器正常工作。 – SLaks 2010-05-17 16:35:48

+2

请确保在IE中测试它,因为它不会让你这样做,至少不是你所拥有的,你将不得不移除/添加一个输入元素,这种类型在IE中是不可变的:) – 2010-05-17 16:36:50

回答

3

如果这是你确切的标记,你可以做到这一点。还要注意,这个更新实际上可以在不同的浏览器上工作。由于您的复选框,目前没有一个ID,我使用的是兄弟选择通过其父p标签来访问它:

jQuery(function($){ // DOM Ready 

    $("#passwordID + p input").click(function(){ 
    var new_type = $(this).is(':checked') ? "text" : "password", 
     pwd  = $("#passwordID"); // We keep replacing it, so find it again 
    if(pwd.attr('type') !== new_type){ 
     pwd.replaceWith( 
      $("<input />", {type: new_type, value: pwd.val(), id: "passwordID", name: "PasswordName"}) 
     ); 
    } 
    }).click(); // Trigger it once on load in case browser has remembered the setting 

}); 

Demo on JSBin

+0

Zounds!我很高兴我问过! – 2010-05-17 17:02:05

+0

+1谢谢你的纠正。我删除了我的答案。 – user113716 2010-05-17 17:11:18

+0

我在JSBin的IE8上试过这个 - 它会显示值,但不会再隐藏它。 – scunliffe 2010-05-17 17:18:57

4

像这样:

$('#ID of CheckBox').change(function() { 
    $('#passwordID').attr('type', this.checked ? 'text' : 'password'); 
}); 
+2

否需要获取底层元素 - $('#passwordID')。attr('type',...) – 2010-05-17 16:38:24

+0

是的,您是对的。 – SLaks 2010-05-17 16:39:24

+1

正如在对原始问题的评论中指出的那样 - 这将在IE浏览器中不工作**,因为IE无法更改类型属性! bug:http://webbugtrack.blogspot.com/2007/09/bug-237-type-is-readonly-attribute-in.html – scunliffe 2010-05-17 16:45:39

相关问题