如何使用纯Javascript在HTML属性中插入变量的值

时间:2017-02-05 11:49:56

标签: javascript html html5

我正在尝试从HTML属性中的url插入一个值,如下所示:

我做了这个功能

function urlId(qs) {
document.getElementsByTagName("BUTTON")[0].setAttribute("data-channel-external-id", "qs.channelid"); 
}
urlId(qs);

我想插入此变量的值qs.channelidqs.channelid是我用来从ex url获取值的函数的变量:www.mysite.com/pagina.php我想要的id = VALOR在HTML属性中获取并设置。 所以我在上面创建了这个代码,并将以下内容放在我的data-channel-external-id="urlId(qs)"属性中,但它不起作用...

2 个答案:

答案 0 :(得分:1)

您不需要引号:"qs.channelid"是静态字符串,而qs是对象,qs.channelid是其动态属性,您想要读取的值。所以它将是:

function urlId(qs) {
  document.getElementsByTagName("BUTTON")[0].setAttribute("data-channel-external-id", qs.channelid); 
}
urlId(qs);

答案 1 :(得分:0)

如果qs是一个函数,则必须先调用该函数才能访问其属性

function qs() {
  // Do something in your function and set channelid on this (the function itself)
  this.channelid = "test";
  return this;
}

function urlId(qs) {
  var qsResult = qs();
  // Call the function, after that, you can access its properties: qs().channelid
  document.getElementsByTagName("BUTTON")[0].setAttribute("data-channel-external-id", qsResult.channelid);
  document.getElementById('channelid').textContent = "Attribute data-channel-external-id=\"" + qsResult.channelid + "\" is set on the button";
}
urlId(qs);
<button id="example" value="example">example</button>
<label id="channelid"></label>

关于您的评论,您可以在代码中的任意位置设置channelid:

function qs(url) {
  // Do something in your function and set channelid on this (the function itself)
  this.channelid = url;
  return this;
}

// pass the url as a parameter
var qsResult = qs("the-url-you-want");
console.log("When using the parameter: qsResult.channelid === \"" + qsResult.channelid + "\"");

// or don't use a parameter and set the url later on
var qsResultWithoutParameter = qs();
console.log("When not using the parameter: qsResultWithoutParameter.channelid === undefined");

// Now set the channelid after the function is called
qsResultWithoutParameter.channelid = "the-url-you-want";
console.log("Setting the channelid after the function is called: qsResultWithoutParameter.channelid === \"" + qsResultWithoutParameter.channelid + "\"");