change type of input field with jQuery

后端 未结 29 2106
青春惊慌失措
青春惊慌失措 2020-11-22 05:13
$(document).ready(function() {
    // #login-box password field
    $(\'#password\').attr(\'type\', \'text\');
    $(\'#passwo         


        
29条回答
  •  一向
    一向 (楼主)
    2020-11-22 05:44

    A more cross-browser solution… I hope the gist of this helps someone out there.

    This solution tries to set the type attribute, and if it fails, it simply creates a new element, preserving element attributes and event handlers.

    changeTypeAttr.js (GitHub Gist):

    /* x is the  element
       type is the type you want to change it to.
       jQuery is required and assumed to be the "$" variable */
    function changeType(x, type) {
        x = $(x);
        if(x.prop('type') == type)
            return x; //That was easy.
        try {
            return x.prop('type', type); //Stupid IE security will not allow this
        } catch(e) {
            //Try re-creating the element (yep... this sucks)
            //jQuery has no html() method for the element, so we have to put into a div first
            var html = $("
    ").append(x.clone()).html(); var regex = /type=(\")?([^\"\s]+)(\")?/; //matches type=text or type="text" //If no match, we add the type attribute to the end; otherwise, we replace var tmp = $(html.match(regex) == null ? html.replace(">", ' type="' + type + '">') : html.replace(regex, 'type="' + type + '"') ); //Copy data from old element tmp.data('type', x.data('type') ); var events = x.data('events'); var cb = function(events) { return function() { //Bind all prior events for(i in events) { var y = events[i]; for(j in y) tmp.bind(i, y[j].handler); } } }(events); x.replaceWith(tmp); setTimeout(cb, 10); //Wait a bit to call function return tmp; } }

提交回复
热议问题