[英]Replace text in paragraph in div by clicking on a span
I am looking to change a paragraph of text into different text by clicking on a fake 'link' (span) at the bottom of the page. 我想通过单击页面底部的假“链接”(跨度)来将一段文本更改为其他文本。
what I have thus far 我到目前为止所拥有的
<body>
<p> here is a paragraph that i would like to change once the span below me is clicked </p>
<span id="click"> click me for the text above me to change </span>
</center>
</body>
<script>
$( "click" ).click(function() {
$( "p" ).replaceWith( "new paragraph" );
});
</script>
I'm really new to jquery and javascript so any help would be appreciated! 我真的是jquery和javascript的新手,所以将不胜感激! thanks.
谢谢。
1st: for id you should use # 第一:要使用ID,请使用#
2nd: to get the previous element use .prev()
.. $(this).prev('p')
第二个:要获取上一个元素,请使用
.prev()
.. $(this).prev('p')
<script>
$( "#click" ).click(function() {
$(this).prev( "p" ).replaceWith( "<p>new paragraph</p>" );
});
</script>
Note: id must be unique so don't use same id for more than one element so try to use class instead
<span class="click">
and then use$('.click')
instead of$('#click')
注意:id必须是唯一的,因此不要对多个元素使用相同的id,因此请尝试使用class代替
<span class="click">
,然后使用$('.click')
代替$('#click')
3rd: what is </center>
in your code should do? 第三:您的代码中
</center>
应该做什么?
4th: you should check to include jquery 第四:您应该检查是否包含jquery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
5th: put script before closing body tag 第五:在关闭正文标签之前放置脚本
full code 完整的代码
<body>
<p> here is a paragraph that i would like to change once the span below me is clicked </p>
<span id="click"> click me for the text above me to change </span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(docuemt).ready(function(){
$( "#click" ).click(function() {
$(this).prev( "p" ).replaceWith( "<p>new paragraph</p>" );
});
});
</script>
</body>
to put img instead of paragraph use 把img而不是段落使用
$(this).prev( "p" ).replaceWith('<img src="http://placehold.it/350x150">');
to put img inside paragraph 将img放在段落中
$(this).prev( "p" ).html( 'new paragraph<img src="http://placehold.it/350x150">' );
$( "click" )
应该是$( "#click" )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.