gpt4 book ai didi

javascript - 如何为具有相同id的动态按钮指定不同的 Action onclick

转载 作者:行者123 更新时间:2023-11-28 16:58:10 24 4
gpt4 key购买 nike

我有三个具有相同 ID 的按钮。它们被动态添加到页面中。

<div class="row" id=rigacite">
<p id="corpo">
some text some text
some text some textsome text some textsome text some textsome text some textsome text some textsome text some textsome text some textsome text some textsome text some textsome text some text
<button id="show"> </button>
</p>
<p id="corpo">
other text other text other text other textother text other textother text other textother text other textother text other textother text other textother text other textother text other textother text other textother text other textother text other textother text other text
<button id="show"> </button>
</p>
<p id="corpo">
another text another textanother textanother textanother textanother textanother textanother textanother textanother textanother textanother text
<button id="show"> </button>
</p>
</div>

当我点击其中一个时,我希望它显示其父项的内容

。每个父级

都有不同的文本。我怎样才能做到这一点?我写这段代码,

var $t = jQuery.noConflict();
$t(document).ready(function() {

$t('#rigacite #corpo').each(function()
{
var maxLength = 90;
var myStr = $t(this).text();

if(myStr.trim().length>maxLength)
{
var newString, removedStr;

newString = myStr.substring(0, maxLength);
removedStr = myStr.substring(maxLength, myStr.trim().length);

$t(this).empty().html(newString);

$t(this).append('<br/><br/><button id="show" class=" btn fa fa-plus-circle"></button>');



$t(document).on("click", "#show", function()
{

$t(this.parentNode).html(newString+removedStr);


});


}
});
});

当我点击第一个时,它起作用了,但是当我点击其他时,显示的是第一个父级的相同文本。有人可以帮我吗?提前谢谢你。

最佳答案

一旦您解决了 HTML 中的 id 问题以使用 class 而不是 id(请参阅 fiddle ),您可以使用如下内容:

$('.show').on('click', function(){
alert($(this).parent().text());
});

Here's a fiddle .

您可以将此句柄直接放在 ready 函数中,而不是将其放在 each() 函数中。

编辑:您在每个函数中所做的整个字符串操作也可以在点击句柄中完成。只需获取按钮父级的字符串;基本上取代这个

var myStr = $t(this).text();  // here 'this' is the paragraph

var myStr = $t(this).parent().text();   // here 'this' is the button

关于javascript - 如何为具有相同id的动态按钮指定不同的 Action onclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31747060/

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