页面上有一个复选框
<input
name='<%=htmlServiceId %>'
<%--class='parent-<%= service.ParentId.Value.GetCustomerServiceId() %>'--%>
class='parent-<%=service.ParentId.Value.GetCustomerCategoryId() %> x-form-checkbox x-form-field'
type='checkbox'
id="<%=htmlServiceId%>"
/>
以下是结果html的外观
<input name="s8" class="parent-s18" id="s8" type="checkbox"/>
在checkBos有一个类(parent-sXX
)之前,我通过这种方式找到了这个checkBox(以及其他类似的)
//........................
var temp = $(this).attr('class').split('-');
var parentId = temp[1];
if ($(this).attr('checked')) {
$('#' + parentId).attr('checked', 'checked');
//.......................
}
}
但是现在checkBox有几个类(parent-sXX x-form-checkbox x-form-field
),通过按类查找checkBox这个解决方案不起作用。
如何解决?
更新:除了使用data
属性之外还有什么方法吗?
答案 0 :(得分:2)
如果您想维护原始代码,可以过滤掉课程。
请参阅:http://jsfiddle.net/mSRZY/
$(':checkbox').change( function() {
//get classes
var getClass = $(this).attr('class');
//seperate them into an array
var classes = getClass.split(' ');
//loop the array, replace getClass if it find the "search param"
$.each(classes, function(index,value) {
if(value.indexOf("parent") != -1) {
getClass = value;
}
});
alert(getClass);
});
答案 1 :(得分:1)
我认为只添加另一个data-
属性并使用它而不是尝试从其中一个类中提取id会更容易..
<input
name='<%=htmlServiceId %>'
<%--class='parent-<%= service.ParentId.Value.GetCustomerServiceId() %>'--%>
class='parent-<%=service.ParentId.Value.GetCustomerCategoryId() %> x-form-checkbox x-form-field'
type='checkbox'
data-parentid="<%= service.ParentId.Value.GetCustomerServiceId() %>"
id="<%=htmlServiceId%>"
/>
并使用
var parentId = $(this).data( 'parentid' );
if ( $(this).attr('checked')) {
$('#' + parentId).attr('checked', 'checked');
<强>更新强>
由于你不能使用data
,这是一种分割类的方法..
var itemClasses = $(this).attr('class').split(' ');
var parentId = '';
for (var i = 0; i < itemClasses.length; i++) {
if (itemClasses[i].indexOf('parent-s') == 0) {
parentId = itemClasses[i].split('-')[1];
break;
}
}
if ($(this).attr('checked')) {
$('#' + parentId).attr('checked', 'checked');
}
答案 2 :(得分:1)
如果您想保留HTML,请从类列表中获取所需的数字 -
var parentId = $(this).attr('class').match(/parent-s(\d+)/)[1];
if ($(this).attr('checked')) {
$('#' + parentId).attr('checked', 'checked');
//.......................
}
答案 3 :(得分:0)
使用数据属性和jQuery data方法:
HTML
<input
name='<%=htmlServiceId %>'
class='x-form-checkbox x-form-field'
type='checkbox'
id="<%=htmlServiceId%>"
data-parentId="<%=service.ParentId.Value.GetCustomerCategoryId() %>"
/>
JS
var parentId = $(this).data('parentId');
if ($(this).attr('checked')) {
$('#' + parentId).attr('checked', 'checked');
}
不使用数据属性,您可以这样做:
var temp = $(this).attr('class').split(' '), parentId;
for (var i = 0; i < temp.length; i++) {
if (temp[i].indexOf('parent-') === 0) {
parentId = temp[i].split('-')[1];
}
}
if ($(this).attr('checked')) {
$('#' + parentId).attr('checked', 'checked');
}