我希望通过点击虚假的链接将一段文字更改为不同的文字。 (跨度)在页面底部。
到目前为止我所拥有的
<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>
我对jquery和javascript真的很新,所以任何帮助都将不胜感激!感谢。
答案 0 :(得分:1)
第一名,您应该使用#
第二名:使用.prev()
来获取上一个元素。$(this).prev('p')
<script>
$( "#click" ).click(function() {
$(this).prev( "p" ).replaceWith( "<p>new paragraph</p>" );
});
</script>
注意:id必须是唯一的,因此不要对多个元素使用相同的ID 因此,请尝试使用类
<span class="click">
,然后使用$('.click')
代替$('#click')
第3名:代码中的</center>
应该是什么?
第4名:您应该检查以包含jquery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
第五:在关闭正文标记之前放置脚本
完整代码
<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>
将img替换为段落使用
$(this).prev( "p" ).replaceWith('<img src="http://placehold.it/350x150">');
将img放入段落
$(this).prev( "p" ).html( 'new paragraph<img src="http://placehold.it/350x150">' );
答案 1 :(得分:0)
$( "#click" )
应为routes.MapRoute(
name: "TempCheck",
url: "{controller}/{action}/{stringParam}",
defaults: new { controller = "Temp", action="CheckParameter",stringParam= UrlParameter.Optional }
);
答案 2 :(得分:0)
实际上你不需要replaceWith()
。您只需使用text()
即可更改文字。
$( "#click" ).click(function() {
$( "p" ).text( "new paragraph");
});