首页 > 解决方案 > 如何从 console.log() 获取有用的信息

问题描述

我正在使用 OpenLayers 和 jQuery 映射具有某些功能及其属性的 GeoJson 文件

我的目标是获取功能的属性列表(名为 my_feature)。

所以,我尝试了下面的代码:

    var list_of_keys = Object.keys(my_feature.getProperties());
    $('<input>').val(list_of_keys).appendTo('body').select();
    document.execCommand('copy');

执行此操作时,列表被成功复制。并且使用(cntl + v),我得到:

几何,名称,refer_desc,refer_de_1,refer_TNZM,refer_TNZV,refer_TNZI,refer_TNZC,refer_MN,refer_MR,refer_MA,refer_AN,refer_AR,refer_AA,refer_VN,refer_VR,refer_VA,refer_PBN,refer_PBR,refer_PBA,refer_de_2

但是这个结果只被复制到剪贴板,并没有分配给我以后可以在代码中使用的变量。

事实上,当我这样做时:

    var list_of_keys = Object.keys(my_feature.getProperties());
    var x = $('<input>').val(list_of_keys).appendTo('body').select();
    console.log(x);

我得到了一个我无法理解的奇怪回报(见图):

在此处输入图像描述

所以我的问题是:

1. Why I am getting different returns with the copy and the console
2. What the return in the console mean 
3. How to get the copied list [geometry,Name,..,refer_de_2] to a variable (for example x = [geometry,Name,..,refer_de_2]) and then use it later in the code

标签: javascriptjqueryopenlayers

解决方案


您正在使用浏览器行为来复制输入值。但是 jQueryselect()总是返回一个 jQuery 对象。

请参阅文档:https ://api.jquery.com/select/

execCommand已弃用,请使用新的剪贴板 API:
https ://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand

https://developer.mozilla.org/en-US/docs/Web/API/Clipboard/writeText

然后你需要剪辑你的list_of_keys变量.join(',')

function setClipboardText(text) {   
    navigator.clipboard.writeText(text).then(
        function () {
        /* success */
        },
        function () {
        /* failure */
        }
    );
}

var list_of_keys = Object.keys(my_feature.getProperties());
console.log(list_of_keys.join(','));

setClipboardText(list_of_keys.join(','));

推荐阅读