使用 jQuery 编辑 innerHTML()

Using jQuery to edit innerHTML()

我是 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);

});

你可以试试这个方法:

$("#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>