2016-06-14 89 views
2

我正在从数据库加载文本字符串,我需要从其父元素访问属性的值。从文本字符串获取属性

字符串:<p lang="en" langDirection="rtl">Stuff and Things</p>

我需要的langDirection从上述代码的值。它应该始终是它的第一个实例,所以我不需要在全局范围内搜索字符串。

我达到我需要的东西,使用的代码我的PHP部分如下:

<?php preg_match('/langDirection="(.+?)"/', $request->requestDescription, $matches); echo $matches[1]; ?> 

谁能推荐的方式与JS/jQuery来做到这一点?

回答

4

这是使用jQuery非常简单:

var strFromServer = '<p lang="en" langDirection="rtl">Stuff and Things</p>'; 
$(strFromServer).attr('langDirection'); 
1

尝试下面的方法。

var $theAttr = $("p").attr("langDirection"); 
 
alert($theAttr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<p lang="en" langDirection="rtl">Stuff and Things</p>

0

你可以使用parseHTML还有:

var el = $.parseHTML("<p lang=\"en\" langDirection=\"rtl\">Stuff and Things</p>"); 
console.log($(el).attr("langDirection")); 

更多信息:https://api.jquery.com/jquery.parsehtml/