我试图在以下操作后获取元素的ID:
我点击一个链接,然后获取其中的文字。然后我想比较该文本以获取包含它的元素。
获取新发现的元素ID。
然而,最新动作会给我一个不确定的结果,所以欢迎你的帮助。
这是我的代码:
$("#mybutton").click(function (e){
e.preventDefault();
var txt = $(e.target).text();
var findTxt = $(".list:contains('txt')");
console.log("findTxt returns : "+ findTxt.attr('id'));
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="mybutton">Sample Text</a>
<span id="idtofind" class="list">Sample Text</span>
<span id="another" class="list">another</span>
<span id="andanother" class="list">and another</span>
&#13;
答案 0 :(得分:0)
您传递字符串'txt'而不是传递变量。
将$(".list:contains('txt')");
替换为$(".list:contains('" + txt + "')");
像这样:
$("#mybutton").click(function (e){
e.preventDefault();
var txt = $(e.target).text();
var findTxt = $(".list:contains('" + txt + "')");
console.log("findTxt returns : "+ findTxt.attr('id'));
});
答案 1 :(得分:0)
border
应为$(".list:contains('txt')");
注意字符串和变量连接。下面应该工作:):
$(".list:contains('"+txt+"')");
&#13;
$("#mybutton").click(function (e){
e.preventDefault();
var txt = $(e.target).text();
var findTxt = $(".list:contains('"+txt+"')");
console.log("findTxt returns : "+ findTxt.attr('id'));
});
&#13;
答案 2 :(得分:0)
您正在寻找一个包含文字文字&#34; txt&#34; - 你想要的是找到包含存储在变量<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="mybutton">Sample Text</a>
<span id="idtofind" class="list">Sample Text</span>
<span id="another" class="list">another</span>
<span id="andanother" class="list">and another</span>
txt
&#13;
$("#mybutton").click(function (e){
e.preventDefault();
var txt = $(e.target).text();
var findTxt = $(".list:contains('" + txt + "')");
console.log("findTxt returns : "+ findTxt.attr('id'));
});
&#13;
答案 3 :(得分:0)
SELECT killer_uid as player_id,
Count(killer_uid) AS player_kills,
Count(victim_uid) AS player_deaths
FROM kill_feed
GROUP BY player_id
ORDER BY player_kills / player_deaths DESC
&#13;
$("#mybutton").click(function(e) {
e.preventDefault();
var txt = $(this).text();
var findTxt = $(".list").filter(function() {
return $(this).text() == txt
})
console.log("findTxt returns : " + findTxt.attr("id"));
});
&#13;
使用<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="mybutton">Sample Text</a>
<span id="idtofind" class="list">Sample Text</span>
<span id="another" class="list">another</span>
<span id="andanother" class="list">and another</span>
答案 4 :(得分:0)
<a href="#" id="mybutton">Sample Text</a>
<span id="idtofind" class="list">Sample Text</span>
<span id="another" class="list">another</span>
<span id="andanother" class="list">and another</span>
-
$("#mybutton").click(function (e){
var txt = $(this).text();
var findTxt = $(".list:contains("+txt+")");
console.log("findTxt returns : "+ findTxt.attr('id'));
});
由于您处于点击按钮的范围内,因此您只需使用this
来引用该按钮。
此外,要获得正确的链接,您需要使用HTML中的href
属性。只需使用href="#"
,也不需要e.preventDefault()
。