javascript - 通过单击跨度替换 div 中段落中的文本

标签 javascript jquery html

我希望通过单击页面底部的虚假“链接”(跨度)将一段文本更改为不同的文本。

到目前为止我所拥有的

<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/

相关文章:

javascript - 点击后如何重置旋转时间

javascript - 用 null 拆分函数参数?

javascript - 为插件 datetimepicker 创建一个allowTimes循环(而不是每个季度硬编码)

javascript - 我希望我的动画在屏幕上水平移动并在我按下停止按钮后停止

html - 当超过div的宽度时如何截断文本

javascript - Angular 2 如何将单选按钮的检查属性绑定(bind)到组件的 bool 属性?

java - 什么时候可以使用 FRAMESET

javascript - Javascript 中的广度优先遍历

javascript - Leaflet 和 MapBox API - 遵循地球形状的曲线

javascript - 使用脚本创建隐藏的输入字段