0

如何增加字符串中最后一个的宽度?我正在尝试使其当前宽度+ 20px;

这是我的小提琴代码

var header="<th id="tblHeader_1" style="width: 80px;"><span>Id</span></th>
<th class="headerSortDown" id="tblHeader_2" style="width: 300px;"><span>Title</span></th>
<th class="headerSortDown" id="tblHeader_3" style="width: 300px;"><span>Adress</span></th>";


//Increase last th width
header.find(th:last).css('width',currentwidth+20+'px');    
alert(header);
4

4 回答 4

2

Try to convert your header to jQuery object using $ in order to use jQuery method here:

$(header).find('th:last').css('width',currentwidth+20+'px');

Also, you need to use ' ' to wrap your string instead of " ":

var header='<th id="tblHeader_1" style="width: 80px;"><span>Id</span></th><th class="headerSortDown" id="tblHeader_2" style="width: 300px;"><span>Title</span></th><th class="headerSortDown" id="tblHeader_3" style="width: 300px;"><span>Adress</span></th>';
于 2014-03-07T08:23:11.693 回答
2

首先,您需要从您的 HTML 字符串创建一个 jQuery 对象,然后您需要th在增加它之前实际获取当前宽度:

th = $(header).find('th:last');
th.css('width', (th.width() + 20) + 'px');
于 2014-03-07T08:29:54.667 回答
1
var header = $('<th id="tblHeader_1" style="width: 80px;"><span>Id</span></th><th class="headerSortDown" id="tblHeader_2" style="width: 300px;"><span>Title</span></th><th class="headerSortDown" id="tblHeader_3" style="width: 300px;"><span>Adress</span></th>');
$(header[header.length-1]).css({width:"+=20"});
alert(header);

在这里演示http://jsfiddle.net/sBbcE/2/

于 2014-03-07T08:35:44.283 回答
1

现场演示过滤器()

这里的问题 JQuery find() 不适用于 HTML String 。首先我们需要注入 DOM 然后它会正常工作。

它可以很好地与filter()方法更好的解释在这里Find element at HTML string

var header='<th id="tblHeader_1" style="width:80px;"><span>Id</span></th><th class="headerSortDown" id="tblHeader_2" style="width: 100px;"><span>Title</span></th><th class="headerSortDown" id="tblHeader_3" style="width:100px;"><span>Adress</span></th>';

var $header =  $(header);

var th = $header.filter("th:last");

th.css('width',th.width() + 50 + 'px');

$header.appendTo('#main');

方法的另一种方式find()

现场演示

var header='<th id="tblHeader_1" style="width:80px;"><span>Id</span></th><th class="headerSortDown" id="tblHeader_2" style="width: 100px;"><span>Title</span></th><th class="headerSortDown" id="tblHeader_3" style="width:100px;"><span>Adress</span></th>';

var currentwidth = 100;

$('#main').append(header).find('th:last').css('background-color','red');//For Testing pu

//Increase last th width
$('#main').find('th:last').css('width',currentwidth + 50 + 'px');

请查看 https://stackoverflow.com/questions/7159426/using-jquery-to-search-a-string-of-html

于 2014-03-07T09:10:13.817 回答