【问题标题】:Using jQuery to edit innerHTML()使用 jQuery 编辑 innerHTML()
【发布时间】:2021-07-13 08:11:03
【问题描述】:

我是 jQuery 的初学者。我正在尝试使页面用用户在按下按钮之前键入的值替换跨度内部 html。

$(document).ready(function() {
      // Get value on button click
      $('button').click(function() {
          var str = $('#formValue').val();
        } else {
          str = "empty"
        }
        $('#adVar').html(str);
      }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="formValue" placeholder="type 
        something here">
<button id="submitButton">enter</button>
<p>So now whatever you put in that field should appear here: "<span id="adVar">this 
         is the value we're replacing</span>".
</p>
function advancedFunction() {
  
  if ( document.getElementById("formValue").value ) {
    // grab the value from the form, but we'll need to set a listener (below) since it changes when you click the button
    var theVar = document.getElementById("formValue").value;
  } else {
    theVar = "empty";
  }
  // now that we have a value for the form field, let's output it to the field
  document.getElementById("advancedVar").innerHTML = theVar;


document.getElementById("submitButton").addEventListener("click", advancedFunction);

});

【问题讨论】:

  • 您的$(document).ready( 未正确关闭。它缺少)
  • 这是完整的代码吗?因为它错过了很多东西。这个sn-p怎么有else声明之前没有if
  • 我正在尝试使用 jquery 重写一个 javascript 函数。我将很快添加。

标签: javascript html jquery innerhtml


【解决方案1】:

你可以试试这个方法:

$("#submitButton").click(function(){
   var value=$("#formValue").val()
   var advar=$('#adVar')
   if(value.length>1){
      advar.html(value);
   }else{
      advar.html("empty");
    }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input id="formValue" placeholder="type something here">
<button id="submitButton">enter</button>
<p>So now whatever you put in that field should appear here: "       
   <span id="adVar">this is the value we're replacing</span>".
</p>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-28
    • 1970-01-01
    相关资源
    最近更新 更多