如果匹配字符串,则更改html的内容

时间:2018-03-28 11:23:54

标签: javascript html

尝试使用if语句来检查一段html是否等于一个字符串,以及它是否确实替换了它。到目前为止,付款方式将更改为待付款,但新的段落元素将不会。 opaymethod动态变化取决于客户如何为物品付款。

HTML

<div class="label">Payment Type:</div>
    <div class="text" id="paymentMethod">[opaymethod]</div>
    <div class="clear"></div>
<div class="element"></div>

JS

$(document).ready(function() {
  var doc = document.getElementById('paymentMethod').innerHTML;
  var res = doc.replace("Account customers", "Payment pending");

  document.getElementById("paymentMethod").innerHTML = res;


  if(document.getElementById('paymentMethod').innerHTML === 'Payment pending'){

    document.getElementById('element').append("<p>Payment Options: Bank payment</p>");
     console.log("inserted");
  }
  else
     console.log("not inserted");    
});

2 个答案:

答案 0 :(得分:1)

我认为这可能是您正在寻找的:

<div class="label">Payment Type:</div>
<div class="text" id="paymentMethod">Payment pending</div>
<div class="clear"></div>
<div class="element" id="element"></div>

<script>
    document.addEventListener('DOMContentLoaded', function(e){
        var paymentMethodElement = document.getElementById('paymentMethod');
        var elementElement = document.getElementById('element');
        paymentMethodElement.innerHTML = "Account customers";

        if( paymentMethodElement.innerHTML == "Account customers" ){
            alert('Payment method == Account customers!');
            elementElement.innerHTML = "<p>Payment Options: Bank payment</p>";

        } else {
            alert('Something went wrong!');
        }
    });
</script>

答案 1 :(得分:0)

当你做追加时,你正在寻找ID的元素,如果你修复元素没有ID但是是class。

更改

<div class="element" id="element"></div>