HTML:
<div>
<label for="mytags">Add tags:</label>
<input name="mytags" id="mytags" type="text" value="1111, 2222, 3333,">
</div>
JS:
this.tags = $("#mytags")
.map(function(){return $(this).val();}).get();
但是我从 value =“ 1111,2222,3333,” 收到文本,而不是我在字段中键入的文本。
如何解决?
此代码来自 uploader API 3 javascript 原始代码是:
var UploadVideo = function() {
/**
* The array of tags for the new YouTube video.
*
* @attribute tags
* @type Array.<string>
* @default ['google-cors-upload']
*/
this.tags = ['youtube-cors-upload'];
...
也许您还有其他想法如何从输入type =“ text”中获取标签?
答案 0 :(得分:1)
this.tags = ['youtube-cors-upload']
通知this.tags
是Array
。如果您用value
中的input
覆盖了它,它将变成String
。您确定那是您想要/需要的吗?
但是,如果您的问题如您所描述的那样简单,那么像这样的解决方案必须起作用:
var mytags = document.getElementById('mytags');
var btn = document.getElementById('btn');
var getAttrValue = document.getElementById('getAttrValue');
btn.addEventListener('click', function() {
// this reads whatever is currently in the input
alert(mytags.value);
})
getAttrValue.addEventListener('click', function() {
// this reads whatever is set in the HTML attribute value on the element
alert(mytags.getAttribute('value'));
})
<div>
<label for="mytags">Add tags:</label>
<input name="mytags" id="mytags" type="text" value="1111, 2222, 3333,">
<button id="btn">Get Tags value from input</button>
<button id="getAttrValue">Get the attribute value instead of the property value</button>
</div>
如果您需要解析输入字段,以使每个逗号分隔的文本成为this.tags
中的数组元素,则需要这样做:
var tags = ['whatever-this-is'];
var tags2 = ['whatever-this-is'];
var mytags = document.getElementById('mytags');
var btn = document.getElementById('btn');
btn.addEventListener('click', function() {
// this reads whatever is currently in the input
// and splits the values into an array
tags = mytags.value.replace(/ /g, '').split(',');
// if all you want is an array with one element
// that is whatever was in the input, do this:
tags2 = [mytags.value];
console.log(tags);
console.log(tags2);
})
<div>
<label for="mytags">Add tags:</label>
<input name="mytags" id="mytags" type="text" value="1111, 2222, 3333,">
<button id="btn">Get Tags value from input and put them in tags array</button>
</div>
如果您还有其他问题,则需要在问题中添加更多信息,我将尝试相应地调整答案。
答案 1 :(得分:1)
根据您的后续编辑,看起来您不仅在尝试检索输入字段的值,而且还在尝试将该值转换为数组。您尝试过的map().get()
东西确实返回了一个数组,但是只返回了一个元素数组(因为您要为它分配一个字符串值)-看起来您打算用逗号分割该字符串:>
var splitTags = function() {
this.tags = $("#mytags")
.val() // get the field value
.split(/\s?,\s?/) // split on commas and (optionally) whitespace
.filter(Boolean); // remove empty elements (caused by leading or trailing commas)
console.log(this.tags);
return this.tags;
}
// demo:
splitTags();
$('#mytags').on("change", splitTags);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<label for="mytags">Add tags:</label>
<input name="mytags" id="mytags" type="text" value="1111, 2222, 3333,">
</div>