2012-08-28 27 views
0

我想将jquery themeroller highlight/error html应用于我的jQuery代码。这是jQuery的亮点代码是这样(错误代码是相似的):将CSS应用于jQuery代码

<div class="ui-widget"> 
    <div class="ui-state-highlight ui-corner-all" style="margin-top: 20px; padding: 0 .7em;"> 
    <p><span class="ui-icon ui-icon-info" style="float: left; margin-right: .3em;"></span> 
    <strong>Hey!</strong> Sample ui-state-highlight style.</p> 
    </div> 
</div> 

我已经构建这样我的代码:

function doAjax(){ 
     $.ajax({ 
      url: 'myfile.php', 
      success: function(data) { 
       if (data == 'Initializing...please wait') 
       { 
        $('#quote p').html(data); //here I would add highlight css code 
        setTimeout(doAjax, 2000); 
       } 
       else 
       { 

        $('#quote p').html(data); //here is error css code 

       } 

      } 
     }); 

    } 

这打印到一个div:

<div id="quote"><p> </p></div> 

使用.css()这里很麻烦,我想。有没有办法将HTML添加到条件?请注意,.html(data)是必要的,因为您从服务器获得不同的消息,除非有其他建议。

回答

1

您可以尝试创建一个小部件来创建元素。

$.widget("jui.highlightBox", { 

    options: { 
     html:'', 
     icon: 'ui-icon-info' 
    }, 

    _create: function() { 
     var wrapper = $('<div>',{'class':'ui-widget'}), 
      container = $('<div>',{'class':'ui-state-highlight ui-corner-all',style:'margin-top: 20px; padding:.7em;'}), 
      icon = $('<span>',{'class':'ui-icon ' + this.options.icon,style:'float: left; margin-right: .3em;'}); 
     wrapper.html(container.html(this.options.html)) 
     .appendTo(this.element); 
     if(this.options.icon != '') 
      icon.prependTo(container); 
    } 
}); 

以及错误文本...

$.widget("jui.errorBox", { 

    options: { 
     html:'', 
     icon: 'ui-icon-alert' 
    }, 

    _create: function() { 

     var wrapper = $('<div>',{'class':'ui-widget'}), 
      container = $('<div>',{'class':'ui-state-error ui-corner-all',style:'margin-top: 20px; padding:.7em;'}), 
      icon = $('<span>',{'class':'ui-icon ' + this.options.icon,style:'float: left; margin-right: .3em;'}); 
     wrapper.html(container.html(this.options.html)) 
     .appendTo(this.element); 
     if(this.options.icon != '') 
      icon.prependTo(container); 
    } 
}); 

你可以用喜欢本作的亮点...

$('<p>').highlightBox({'html':data}).appendTo('#quote'); // highlight 

...这为错误文本

$('<p>').errorBox({'html':data}).appendTo('#quote'); // error 

所以你的功能现在看起来像这...

function doAjax(){ 
     $.ajax({ 
      url: 'myfile.php', 
      success: function(data) { 
       if (data == 'Initializing...please wait') 
       { 
        $('<p>').highlightBox({'html':data}).appendTo('#quote'); 
        setTimeout(doAjax, 2000); 
       } 
       else 
       { 

        $('<p>').errorBox({'html':data}).appendTo('#quote'); 

       } 

      } 
     }); 

    } 

而且因为这会让人产生<p>标签,你可以从HTML中删除它...

<div id="quote"></div> 

我很惊讶的是,JQuery的用户界面不会有一个内置已经在这个小部件。

+0

令人惊叹的是,感谢所有的努力。这比我想象的更复杂。 – Tom