简体   繁体   English

jQuery prepend() 和 Append() 不起作用,出了什么问题

[英]jQuery prepend() and Append() not working, what is wrong

My jquery我的 jquery

var proQty = $(".quantitybox");
proQty.prepend('<span class="dec changebtn">-</span>');
proQty.append('<span class="inc changebtn">+</span>');
proQty.on('click', '.changebtn', function () {

My HTML code我的 HTML 代码

<div class="cart-modal-price">
    <p>Fruits</p>
    <p>Price: Ksh. 120/-</p>
    <input type="number" class="quantitybox" placeholder="1">
</div>

Try this.尝试这个。

 var proQty = $(".quantitybox"); proQty.prepend('<span class="dec changebtn">-</span>'); proQty.append('<span class="inc changebtn">+</span>');
 <script src="https://code.jquery.com/jquery-3.5.1.js"></script> <div class="cart-modal-price"> <p>Fruits</p> <p>Price: Ksh. 120/-</p> <span class="quantitybox"><input type="number" placeholder="1"></span> </div>

You are searching for before() and after()您正在搜索before()after()

 var proQty = $(".quantitybox"); proQty.before('<span class="dec changebtn">-</span>'); proQty.after('<span class="inc changebtn">+</span>');
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="cart-modal-price"> <p>Fruits</p> <p>Price: Ksh. 120/-</p> <input type="number" class="quantitybox" placeholder="1"> </div>

Your code didn't work because (as per comment from Andreas )您的代码不起作用,因为(根据Andreas 的评论

"The .prepend() method inserts the specified content as the first child of each element in the jQuery collection", "The .append() method inserts the specified content as the last child of each element in the jQuery collection" - An <input /> element has no children. " .prepend()方法将指定内容作为 jQuery 集合中每个元素的第一个子元素插入", " .append()方法将指定内容作为 jQuery 集合中每个元素的最后一个子元素插入" - An <input />元素没有子元素。

You should be using https://api.jquery.com/after/ & https://api.jquery.com/before/ . You should be using https://api.jquery.com/after/ & https://api.jquery.com/before/ .

after : Insert content, specified by the parameter, after each element in the set of matched elements. after :在匹配元素集中的每个元素之后插入由参数指定的内容。

before : Insert content, specified by the parameter, before each element in the set of matched elements. before :在匹配元素集中的每个元素之前插入由参数指定的内容。

 var proQty = $(".quantitybox"); proQty.before('<span class="dec changebtn">-</span>'); proQty.after('<span class="inc changebtn">+</span>');
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script> <div class="cart-modal-price"> <p>Fruits</p> <p>Price: Ksh. 120/-</p> <input type="number" class="quantitybox" placeholder="1" /> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM