简体   繁体   English

从 select 和 jQuery 选择值时如何更改 Div 内容?

[英]How to change a Div content when selecting a value from a select with a jQuery?

Hi I'm new to jQuery and I'm trying to solve this:嗨,我是 jQuery 的新手,我正在尝试解决这个问题:

When selecting a value from the dropdown ( <select> ), you need to change the content of the div tag (in red) with the selected value.从下拉列表 ( <select> ) 中选择一个值时,您需要使用所选值更改 div 标签(红色)的内容。 Please use jQuery to solve this test, and please don't add any id/class to the above HTML code!请使用jQuery来解决这个测试,并且请不要在上面的HTML代码中添加任何id/class!

I already wrote a script but it does not work, can you help please我已经写了一个脚本但是它不起作用,你能帮忙吗

 var content = $( "div:gt(5)" ); $( "select" ).on( "click", function( event ) { content.html('6 products'); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="toolbar-wrapper"> <div> <div> <label>Product Count</label> <div class="select-group"> <select> <option value="4 products" selected="selected">4 products</option> <option value="6 products">6 products</option> <option value="8 products">8 products</option> </select> </div> </div> <div>4 products</div> </div> </div>

Use this.value in the event handler to get the value that was selected in the dropdown.在事件处理程序中使用this.value来获取在下拉列表中选择的值。

When you select something from the dropdown, the change event is triggered, not click .当您 select 从下拉列表中选择某项时,会触发change事件,而不是click

div:gt(5) is not the correct selector for the div where the result should be displayed. div:gt(5)不是应显示结果的 div 的正确选择器。 Numbering starts from 0 , so it's DIV number 4 .编号从0开始,所以它是 DIV 号4 You can use .eq(4) to select that.您可以使用.eq(4)到 select 那个。

 var content = $("div").eq(4); $("select").on("change", function(event) { content.html(this.value); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="toolbar-wrapper"> <div> <div> <label>Product Count</label> <div class="select-group"> <select> <option value="4 products" selected="selected">4 products</option> <option value="6 products">6 products</option> <option value="8 products">8 products</option> </select> </div> </div> <div>4 products</div> </div> </div>

You can target with > & position selectors .您可以使用> & position 选择器进行定位。

$( "select" ).on( "change", function( event ) {
  $('.toolbar-wrapper > div > div:nth-child(2)').html(event.target.value);
});

Fiddle !小提琴

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

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