开发者

Why would javascript add a random style tag?

I'm using a script I found online to add input prompts on an html form. I got it all working, but now the code is randomly generated a style tag that's throwing off my css. The code is supposed to produce span tags that look like this:

<span id="input-prompt-0" clas开发者_开发技巧s="input-prompt">Company Name</span>

For every text input field. Instead it keeps giving me this:

<span id="input-prompt-0" class="input-prompt" style="display: block;">Company Name</span>

Any ideas why?

Here's the code:

$(document).ready(function(){
  $('input[type=text][title],input[type=password][title],textarea[title]').each(function(i){
    $(this).addClass('input-prompt-' + i);
    var promptSpan = $('<span class="input-prompt"/>');
    $(promptSpan).attr('id', 'input-prompt-' + i);
    $(promptSpan).append($(this).attr('title'));
    $(promptSpan).click(function(){
      $(this).hide();
      $('.' + $(this).attr('id')).focus();
    });
    if($(this).val() != ''){
      $(promptSpan).hide();
    }
    $(this).before(promptSpan);
    $(this).focus(function(){
      $('#input-prompt-' + i).hide();
    });
    $(this).blur(function(){
      if($(this).val() == ''){
        $('#input-prompt-' + i).show();
      }
    });
  });
});


The line $('#input-prompt-' + i).show(); is modifying the style. From the docs on jQuery.show:

The matched elements will be revealed immediately, with no animation. This is roughly equivalent to calling .css('display', 'block'), except that the display property is restored to whatever it was initially.

I guess the more prominent question is why this is "throwing off [your] css"?


This line of code adds the style attribute:

$('#input-prompt-' + i).show();

You can instead use:

$('#input-prompt-' + i).css("display", "");

That will show the span and eliminate the style attribute.


The problem is most likely related to you using .show() and .hide().

These functions alter the style of the element to do their magic.


JQuery show() and hide() functions modified the styles

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜