如何在标题中附加所选选项 [英] How Do I Append The Selected Option In Heading
问题描述
我在js代码中需要帮助
小提琴在这里 - http://jsfiddle.net/wnmcL/781/ [ ^ ]
我想在H3标签中添加所选选项的值。所以,如果我选择'title1',那么h3标签应该具有值hello,这是:title1。
请让我知道如何才能解决这个问题,截至目前我只是让id相同并试图获得价值。它在输入标签中工作正常但不适用于h3。
Hi ,
I need help in js code
The Fiddle is here - http://jsfiddle.net/wnmcL/781/[^]
I want to add the value of the selected option in the H3 Tag . So , As per fiddle if i select 'title1' then h3 tag should have the value hello this is : title1.
Please let me know how can i solve this issue , as of now i am just making the id same and trying to get the value .Its working fine in input tag but not working for h3.
推荐答案
错误的代码,不是真的使用jQuery。 1)你不能指望你h3
如果你什么都不做,内容会更新;您只更新输入
控件;我不知道为什么; 2)你不需要使用document.getElementById
,因为你可以使用jQuery 选择器;另外,避免两次获得相同的元素,重用获取元素的结果;这个操作很贵;更重要的是,在编程中,重要的是永远不要重复任何代码。
这是修复的简单示例。首先,将id
属性添加到您的h3
中的一些唯一值:
Bad code, not really using jQuery. 1) You cannot expect that youh3
content is updated if you are doing nothing about it; you are updating onlyinput
control; I don't know why; 2) you don't need to usedocument.getElementById
, because you can use jQuery selectors; also, avoid getting the same element twice, reuse the result of getting an element; this operation is expensive; more importantly, in programming, its important to never repeat any code.
Here is the simple example of the fix. First, add the attributeid
with some unique value to yourh3
:
<h3 id="div">No need to add "span" here, use some appropriate text, possibly empty!</h3>
现在,Javascript可以更改类似
Now, Javascript can be changed to something like
function run() {
( #div)。text( 所选值为: +
("#div").text("Selected value is: " +
( #选择跨度>)VAL())。
}
("#select").val()); }
不要忘记包含jQuery;它没有在你的代码中完成。
工作,测试。谢谢你允许我使用你的jsFiddle。
有不同的方法可以注意初步选择。例如,选择HTML中的所选项目:
Don't forget to include jQuery; it wasn't done in your code.
Working, tested. Thank you for letting me to use your jsFiddle.
There are different ways to take care about initial selection. For example, chose the selected item in HTML:
<select id="select" onchange="run()">
<option value="0" id="0">Select</option>
<option value="1" id="title 1" selected="true">title 1</option>
<option value="2" id="title 2">title 2</option>
<option value="3" id="title 3">title 3</option>
<!-- spelling fixed... :-) -->
</select>
然后只需先调用你的函数运行
,即可将 div
文本与此选项同步。我想你应该知道jQuery中文档就绪事件的所有内容初始化的规范方法: http:// learn .jquery.com / about-jquery / how-jquery-works [ ^ ]:
and then just call your function run
earlier, to synchronize your div
text with this selection. I think you should know the canonical way of initialization of everything on document ready event in jQuery: http://learn.jquery.com/about-jquery/how-jquery-works[^]:
这篇关于如何在标题中附加所选选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!