gpt4 book ai didi

javascript - JQuery:如何在类名中使用小数来获取文本?

转载 作者:行者123 更新时间:2023-11-28 18:56:55 25 4
gpt4 key购买 nike

以下是类名

<p class="question3.1">Question 3.1</p>
<p class="question3.10">Question 3.10</p>
<p class="question3.11">Question 3.11</p>
<p class="question3.12">Question 3.12</p>

我想在 JQuery 中获取文本 3.1 的值:

alert($("p[class*='question3.1']").text())

它返回所有问题的文本,即

Question 3.1Question 3.10Question 3.11Question 3.12

但是如果我使用以下内容,那么它工作正常。

alert($("p[class*='question3.10']").text())

我怎样才能只选择question3.1的文本?

我无法重构 HTML。

fiddle : https://jsfiddle.net/e9w9fhyw/

最佳答案

那些类名太疯狂了。

不过,您可以选择它们。您有两个选择:

  1. . 进行转义的类选择器,以及

  2. 以空格分隔的属性选择器 (~=)

转义类选择器

第一个的 CSS 类选择器是

.question3\2e\31

\2e 是点,然后因为点后面恰好是一个数字,可以将其纳入转义序列中,所以我们使用 \31对于1

要在 jQuery 选择器中写入,您必须转义反斜杠,因此要获取第一个反斜杠,您可以使用:

$(".question3\\2e\\31").text()

实例:

document.body.insertAdjacentHTML(
"beforeend",
"The first one is: " + $(".question3\\2e\\31").text()
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p class="question3.1">Question 3.1</p>
<p class="question3.10">Question 3.10</p>
<p class="question3.11">Question 3.11</p>
<p class="question3.12">Question 3.12</p>
<hr>

空格分隔的属性选择器

whitespace-separated attribute selector [att~="val"]...

Represents an element with the att attribute whose value is a whitespace-separated list of words, one of which is exactly "val". If "val" contains whitespace, it will never represent anything (since the words are separated by spaces). Also if "val" is the empty string, it will never represent anything.

所以:

$('[class~="question3.1"]').text()

实例:

document.body.insertAdjacentHTML(
"beforeend",
"The first one is: " + $('[class~="question3.1"]').text()
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p class="question3.1">Question 3.1</p>
<p class="question3.10">Question 3.10</p>
<p class="question3.11">Question 3.11</p>
<p class="question3.12">Question 3.12</p>
<hr>

关于javascript - JQuery:如何在类名中使用小数来获取文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33433137/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com