2012-08-28 29 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