停止将占位符插入代码中

时间:2013-04-04 02:47:57

标签: jquery forms field

我有这个jQuery编辑textarea中的代码,从插入到字段中的内容。你可以看到它here。问题是如果用户没有将某些东西放入其中一个字段中,占位符就会插入到代码中。相反,我希望常规标识符保留在那里,而不是在字段留空时替换它们。

这是jQuery代码。

$(document).ready(function(){
    var basicHtml = ($('.code').html()).replace(/&lt;/g,'<').replace(/&gt;/g,'>');

    $('.code').val(basicHtml);

    $('form').on('submit',function() {
        var content = basicHtml;
        content = content.replace(/%name%/g, ($('#name').val()||$('#name').attr('placeholder')));
        content = content.replace(/%slogan%/g, ($('#slogan').val()||$('#slogan').attr('placeholder')));
        content = content.replace(/%description%/g, ($('#description').val()||$('#description').attr('placeholder')));
        content = content.replace(/%bio%/g, ($('#bio').val()||$('#bio').attr('placeholder')));
        content = content.replace(/%analytics%/g, ($('#analytics').val()||$('#analytics').attr('placeholder')));
        content = content.replace(/%favicon%/g, ($('#favicon').val()||$('#favicon').attr('placeholder')));
        var final = content.replace(/%dribbble_username%/g, ($('#dribbble').val()||$('#dribbble').attr('placeholder')));
        $('.code').val(final);

        return false;
    }).on('reset',function(){
        $('form textarea:not(.code),form input').val();
        $('.code').val(basicHtml);
    });

});

谢谢!

1 个答案:

答案 0 :(得分:1)

您基本上是通过阅读占位符属性来设置它。固定代码:

$(document).ready(function(){
    var basicHtml = ($('.code').html()).replace(/&lt;/g,'<').replace(/&gt;/g,'>');

    $('.code').val(basicHtml);

    $('form').on('submit',function() {
        var content = basicHtml;
        content = content.replace(/%name%/g, ($('#name').val()));
        content = content.replace(/%slogan%/g, ($('#slogan').val()));
        content = content.replace(/%description%/g, ($('#description').val()));
        content = content.replace(/%bio%/g, ($('#bio').val()));
        content = content.replace(/%analytics%/g, ($('#analytics').val()));
        content = content.replace(/%favicon%/g, ($('#favicon').val()));
        var final = content.replace(/%dribbble_username%/g, ($('#dribbble').val()));
        $('.code').val(final);

        return false;
    }).on('reset',function(){
        $('form textarea:not(.code),form input').val();
        $('.code').val(basicHtml);
    });

});