简体   繁体   English

如何获得包含一些文本的div

[英]How to get div containing some text

HTML: HTML:

<div class="linkL 01 mp3/01.mp3 imgT/03.jpg">lorem1 - part1</div>
<div class="linkL 02 mp3/02.mp3 imgT/03.jpg">lorem2 - part2</div>
<div class="linkL 03 mp3/03.mp3 imgT/03.jpg">lorem3 - part3</div>

Javascript: 使用Javascript:

var numera = window.location.hash;
var numera  = numera.replace("#","");
console.log(numera); // `part3`
var author = $(".linkL:contains(numera)").html().split(" - ")[0];  

I would like to have the result of lorem3 lorem3的结果

But this is what the console says: 但这就是控制台所说的:

index.js:37 Uncaught TypeError: Cannot read property 'split' of undefined

The way that you are concatenating the value is wrong, 你连接这个值的方式是错误的,

var author = $(".linkL:contains(" + numera + ")").text().split(" - ")[0]; 

You have to concatenate the variable using + , If you don't then that variable name would be considered as a plain string. 您必须使用+连接变量,如果不这样,则该变量名称将被视为纯字符串。 That value it holds will not be concatenated. 它所拥有的价值不会被连接起来。

And the class name that you are using mp3/01.mp3 is invalid. 您使用mp3/01.mp3的类名无效。 A valid class name should follow this rules. 有效的类名应遵循规则。

If you need to find lorem3, then you could loop through each of the divs looking for it. 如果你需要找到lorem3,那么你可以遍历每个div寻找它。

  $(".linkL:contains(" + numera + ")").each(function() {
var author = $(this).text().split(" - ")[0];
if (author == "lorem3") {
  $(".result").text($(this).attr('class'));
}});

jsfiddle example jsfiddle的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM