[英]how to get a part of attribute value?
问:
如果我有一个具有特定类名的div并知道一个标题(属性),那么如何使用Jquery获得此标题值的特定部分?
源代码:(来自fire bug)
<div style="height: 21px; width: 90%; left: 0%;" class="rsApt" title="WPF[003]" id="rs_7_0">
<div style="background-color: rgb(102, 204, 102);" class="rsAptOut">
<div class="rsAptMid">
<div class="rsAptIn">
<div class="rsAptContent">
WPF[003]<a href="#" class="rsAptDelete" style="visibility: hidden;">delete</a>
</div>
</div><div style="z-index: 80;" class="rsAptResize">
<!-- -->
</div>
</div>
</div>
</div>
如果我想获得title属性的003
部分(可能是其他Divs中具有相同类的其他数字),该怎么做? 如果有任何通用的方法来获取字符串的一部分,那将是很棒的。
我想根据以下代码使用此值设置下拉列表的选定值:
$(document).ready(function() {
$(".rsAptContent").click(function(e) {
if ($(e.target).hasClass('rsAptDelete')) {
}
else {
$("#ddl_editCourse").val('The accessed value of the Div title');
ShowDialog(true);
e.preventDefault();
}
});
如何用这行代码做到这一点?
已编辑
谢谢。
var regex = new RegExp("\\[(.*)\\]");
$("#ddl_editCourse").val(regex.exec($(".rsApt").attr("title"))[1]);
您可以在此处使用正则表达式,也可以使用substring
和indexOf
方法。
如果您知道数字将始终在方括号内,则可以使用indexOf查找它们,并基于这些索引获取子字符串:
var title = $('#rsApt').attr('title');
var opening = title.indexOf('[');
var closing = title.indexOf(']');
var number = title.substring(opening, closing);
//打印号码
$("#ddl_editCourse").val('The accessed value of the Div title: ' + number);
$("#ddl_editCourse").val(new RegExp(/\d{3}/).exec( $(".rsApt").attr("title") ));
$("#ddl_editCourse").val( $(".rsApt").attr("title").replace(/\D/g,'') );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.