将 $(this).text 与类内容一起使用



我希望click函数的文本是最后一个变量,但$(this).text似乎没有产生这样的结果。把班级放在最后给了我两条p线。我只想要我正在点击的那个。

编辑: 很抱歉不清楚。尝试将文本附加到输入中,就像我单击它一样多,但只有我实际单击的项目。我不希望两者同时复制。所以我可能会再次单击第 1 段,然后单击第 2 段,然后单击第 1 段而不会覆盖

$(document).ready(function() {
$(".p1").click(function() {
$("input").val(function(index, val) {
return val + $(this).text
})
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<p class=p1>This is a paragraph.</p>
<p class=p1>Another paragraph.</p>
<input>

错误显示:

function(e){return $(this,function(e){return void 0===e?S.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=e)})},null,e,arguments.length)}
Try this hope so it works
$(document).ready(function() {
$(".p1").click(function() {
$("input").val($(this).html())
})
})

看来我想通了。对于混乱,我深表歉意。 VAR X 之前的 Val 函数运行良好。

$(document).ready(function() {
$(".p1").click(function() {
var x = $(event.target).text();
$("input").val((function(index, val) {
return val + x
}))
})
})

您是否正在尝试实现这一目标

$(document).ready(function() {
$(".p1").click(function() {
$("input").val($("input").val() + $(this).text());
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<p class=p1>This is a paragraph.</p>
<p class=p1>Another paragraph.</p>
<input>

希望对你有帮助

最新更新