作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有三个具有相同 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/
我是一名优秀的程序员,十分优秀!