我希望通过单击页面底部的虚假“链接”(跨度)将一段文本更改为不同的文本。
到目前为止我所拥有的
<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 非常陌生,所以任何帮助将不胜感激!谢谢。
最佳答案
1st: 对于 id,您应该使用 #
第二: 要获取前一个元素,请使用 .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')
第三:什么是 </center>
在你的代码中应该做什么?
第四:你应该检查是否包含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">' );
关于javascript - 通过单击跨度替换 div 中段落中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34029413/