Jquery样式div并根据div标签添加标题

时间:2013-01-04 15:04:46

标签: javascript jquery

大家好,我有一个非常标准的div与css,我想附加到已经存在给定类的div。 这是我的标记

<div id ="one" class="PortalBox">

     </div>

   <div class="ab_Box1d">
                <div style="width:600px;">
                    <%@ include file="./concur-reports/index.html"%> 
                </div>
    </div> <!--finish ab_box1d-->  


</div>

这是我的jquery。

 $(document).ready(function() {
$(".PortalBox").each(function(){
    var ThisCss = $('<div class="ab_Box1a" id="report1" style="width:640px; padding-top:6px;">'+   
            '<div class="ab_Box1b" id="reportchild1"> </div>' +
                '<table class="ab_Box1c" width="100%" border="0"'+
                  'cellspacing="0" cellpadding="0">'+
              '<tr>'+
                  '<td style="text-align:left">Concur Reports</td>'+
              '</tr>'+
          '</table>'
   +
     '</div>' )
     ThisCss.insertAfter('.PortalBox');
   });
});

所以基本上我试图在jquery中添加标记,当我偶然发现任何带有“PortalBox”类的div但是我需要创建一个动态的部分,它基本上是一个标题 这部分

 '<td style="text-align:left">my channel</td>'+

需要动态来从另一个带有div的HTML属性中获取标题。  我可以使用值为div标签添加“title”属性,如何使用jquery实现这一点?或java脚本我对任何想法都是开放的,所以备用解决方案。 提前致谢。

2 个答案:

答案 0 :(得分:1)

将标题放在data-*属性中:

<div data-title="my channel" class="PortalBox"></div>

然后您可以使用jQuery检索它:

$('.PortalBox').data('title');

这是完整的代码:

$(document).ready(function() {
    var report = $('<div class="ab_Box1a" style="width:640px; padding-top:6px;">'+   
        '<div class="ab_Box1b" ></div>' +
        '<table class="ab_Box1c" width="100%" border="0"'+
        'cellspacing="0" cellpadding="0">'+
        '<tr>'+
        '<td style="text-align:left">Concur Reports</td>'+
        '</tr>'+
        '</table>'+
        '</div>');

    $(".PortalBox").each(function() {
        report.clone()
            .find('td').text( $(this).data('title') )
            .appendTo(this);
    });
});

请注意,构建像这样的HTML片段非常容易出错。如果你发现自己经常这样做,你应该考虑使用模板系统。

答案 1 :(得分:0)

$('div selector').attr('title', enterDesiredvalue);