使用<select>将“Same”多个<button>函数转换为通用函数

时间:2017-03-08 18:31:23

标签: javascript jquery html select option

我有多个按钮,都做了非常相似的事情。我如何使用&lt; select&gt;带有一个&lt; button&gt;的盒子用更少的javascript做同样的事情? 这些是我想变成&lt; select&gt;的按钮。只有一个按钮的盒子: &lt; button onclick =“SaveAsHTML()”&gt;另存为HTML&lt; / button&gt; &lt; button onclick =“SaveAsJS()”&gt;另存为JS&lt; / button&gt; &lt; button onclick =“SaveAsCSS()”&gt;另存为CSS&lt; / button&gt; &lt; button onclick =“SaveAsTXT()”&gt;另存为TXT&lt; / button&gt; 这是我现在的javascript: 函数SaveAsHTML() {     var filename = document.getElementById(“txtFilename”)。value;     var filename = filename +“。html”; } 功能SaveAsCSS() {     var filename = document.getElementById(“txtFilename”)。value;     var filename = filename +“。css”; } 函数SaveAsJS() {     var filename = document.getElementById(“txtFilename”)。value;     var filename = filename +“.JS”; } 函数SaveAsTXT() {     var filename = document.getElementById(“txtFilename”)。value;     var filename = filename +“。txt”; }

1 个答案:

答案 0 :(得分:1)

这是一个片段,我认为不需要太多解释。

我创建了一个文件类型数组,并使用jquery用<select>填充<option>。然后,当您单击save按钮...

时,我只查看选择了哪一个

var types = [
  {"extension": "html", "name": "HTML"},
  {"extension": "txt", "name": "Plain Text"},
  {"extension": "js", "name": "Javascript"},
  {"extension": "css", "name": "CSS"},
]
types.forEach(function(type) {
  $opt = $("<option>").attr("value", type.extension).text(type.name)
  $("#saveas").append($opt)
})

function SaveAsType()
{
    console.log($("#saveas").val())
    /**
     * Put your code here and replace:
     document.getElementById("inputFileNameToSaveAs").value + ".html";
     * with
     document.getElementById("inputFileNameToSaveAs").value + "." + $("#saveas").val();
     */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Save as <select id="saveas">
</select><button onclick="SaveAsType()">save</button>