I have matching text in different parts of a document. The first is a set of "tags" in a table like so:
我在文档的不同部分有匹配的文本。第一个是表中的一组“标记”,如下所示:
<div id="my-div">
<div><a href="#">tag 1</a></div>
<div><a href="#">tag 2</a></div>
</div>
Then in several other parts of the document, I have a hidden element after the items I want to highlight when the matching link is selected like so:
然后在文档的其他几个部分中,在选择匹配链接时,我想要突出显示的项目后面有一个隐藏的元素,如下所示:
<div class="hide-me">tag 1</div>
Then my click function is like this:
然后我的点击函数是这样的:
$('#my-div a').click(function() {
var txt = $(this).text();
console.log(txt);
});
The output is an empty string, but I’m not sure why.
输出是一个空字符串,但我不确定为什么。
3 个解决方案
#1
58
your code seems to be correct, try this one too.
您的代码似乎是正确的,也试试这个。
$('#my-div a').click(function(e) {
var txt = $(e.target).text();
console.log(txt);
});
#2
0
In your case I wouldn't use the text of the link, as it's possible it may change in the future (ie. you need to translate your website). The better solution is to add custom attribute to links:
在您的情况下,我不会使用链接的文本,因为它可能会在将来发生变化。你需要翻译你的网站)。更好的解决方案是向链接添加自定义属性:
<div id="my-div">
<div><a href="#" sectionId="someId1">tag 1</a></div>
<div><a href="#" sectionId="someId2">tag 2</a></div>
</div>
And then put the id of the hidden tag there, so you and up with:
然后把隐藏标签的id放在那里,你和:
$('#my-div a').click(function() {
var sectionId = $(this).attr('sectionId');
$('#' + sectionId).show();
return false; // return false so the browser will not scroll your page
});
#3
-2
$('#my-div a') is ambiguous.
$(" # div标签”)是模棱两可的。
It goes to read all the a tags within '#my-div'
它会读取" # y-div "中的所有标签
U need to specify which of the 2 tags is clicked..
你需要指定哪两个标签被点击。
#1
58
your code seems to be correct, try this one too.
您的代码似乎是正确的,也试试这个。
$('#my-div a').click(function(e) {
var txt = $(e.target).text();
console.log(txt);
});
#2
0
In your case I wouldn't use the text of the link, as it's possible it may change in the future (ie. you need to translate your website). The better solution is to add custom attribute to links:
在您的情况下,我不会使用链接的文本,因为它可能会在将来发生变化。你需要翻译你的网站)。更好的解决方案是向链接添加自定义属性:
<div id="my-div">
<div><a href="#" sectionId="someId1">tag 1</a></div>
<div><a href="#" sectionId="someId2">tag 2</a></div>
</div>
And then put the id of the hidden tag there, so you and up with:
然后把隐藏标签的id放在那里,你和:
$('#my-div a').click(function() {
var sectionId = $(this).attr('sectionId');
$('#' + sectionId).show();
return false; // return false so the browser will not scroll your page
});
#3
-2
$('#my-div a') is ambiguous.
$(" # div标签”)是模棱两可的。
It goes to read all the a tags within '#my-div'
它会读取" # y-div "中的所有标签
U need to specify which of the 2 tags is clicked..
你需要指定哪两个标签被点击。