如何访问通过JavaScript动态创建的按钮的innerHTML

时间:2015-06-03 07:14:35

标签: javascript html

这是一个用于创建动态按钮的JavaScript函数。我想访问button的innerHTML。

function mynumber() {   
    var i,j = 1, num = 0; # i used for making three buttons in row and j used for repeat same process no of time and num is int text on button
    do {
        for (i = 1; i <= 3; i++) {       
            var btn = document.createElement("BUTTON"); # create button using javascript
            var txt = document.createTextNode(num++); # creat text on button
            btn.appendChild(txt); # attached text on button
            btn.id = ('obj'+ k++) ;  
            document.getElementById("btnsize").appendChild(btn); # atache button with text in div 
        } 
        var next = document.createElement("BR");
        document.getElementById("btnsize").appendChild(next);
        j++;
    } 
    while(j<4)          
}

("btn").click(function()
                     {
                       var val = document.getElementById(this.id).innerHTML;
                           document.getElementById("demo").value = val;
                                    }) 

3 个答案:

答案 0 :(得分:0)

在脚本代码中使用以下脚本,其中&#34; 100&#34;是你想要给出的变量,但那是一个数字;)

btn.style.width="100px"
btn.style.height="100px"

答案 1 :(得分:0)

您可以将css类应用于该按钮,如https://jsfiddle.net/3u71kzrh/

所示

在样式表中或在html <style>中的</style><head>标记之间声明如下样式。

.aClassName{
   width:40px;
   height:40px;
}

在创建按钮元素的代码下方添加以下行。

btn.className = "aClassName";

答案 2 :(得分:0)

首先,我将您的<button> - 创建脚本更改为以下内容:

function mynumber () {
    // a reference to the element to which we want
    // to add the newly-created <button> elements:
    var appendTo = document.getElementById('btnsize'),

        // creating a document fragment to contain
        // the elements to be added; to prevent the
        // document from redrawing every time an
        // element is added:
        fragment = document.createDocumentFragment(),

        // creating a <button> element:
        button = document.createElement('button'),

        // creating a <br> element:
        br = document.createElement('br'),

        // initialising an empty variable, for
        // use within the loop:
        clone;

    // you want nine buttons, so use one loop
    // that will run nine times:        
    for (var i = 0; i < 9; i++) {

        // using the empty variable to
        // hold the cloned <button> element:
        clone = button.cloneNode();

        // setting the text of the <button>
        // to the current index/iteration
        // (i) of the loop:
        clone.textContent = i;

        // appending the cloned <button>
        // to the document fragment:
        fragment.appendChild(clone);

        // we want rows of three, but
        // JavaScript is zero-based, so
        // we add 1 to i, and check the
        // remainder of the division by
        // 3; if it's zero the number is
        // evenly-divisible by 3 therefore
        // it's time to add a <br>:
        if ((i+1)%3 === 0) {

            // appendin a cloned <br> element:
            fragment.appendChild(br.cloneNode())
        }
    }

    // appending the fragment to the
    // container element:
    appendTo.appendChild(fragment);
}

// calling the function:
mynumber();

function mynumber() {
  var appendTo = document.getElementById('btnsize'),
    fragment = document.createDocumentFragment(),
    button = document.createElement('button'),
    br = document.createElement('br'),
    clone;

  for (var i = 0; i < 9; i++) {
    clone = button.cloneNode();
    clone.textContent = i;
    fragment.appendChild(clone);
    if ((i + 1) % 3 === 0) {
      fragment.appendChild(br.cloneNode())
    }
  }
  appendTo.appendChild(fragment);
}

mynumber();
<div id="btnsize"></div>

外部JS Fiddle demo,用于实验。

但是,因为我希望能够改变一切 - 而有助于满足您的尺寸要求 - 我将其修改为以下内容,允许您调用该功能,并提供一些用户定义的选项:

// the 'opts' is an Object, containing
// user-defined settings:
function mynumber(opts) {

    // these are the defaults:
    var settings = {
        'container': 'btnsize',
            'elements': 'button',
            'elementClass': 'newButton',
            'height': 'equal',
            'width': 'equal',
            'rows': 3,
            'cols': 3
    };

    // here we iterate over the properties in the
    // opts Object, using for...in:
    for (var property in opts) {

        // if the object's property is user-defined:
        if (opts.hasOwnProperty(property)) {

            // we update the settings property to
            // match (note: no sanity-checking):
            settings[property] = opts[property];
        }
    }

    // finding the element to which we're appending the
    // content; using the settings.container property
    // (which should contain the 'id' of the element,
    // as we're using document.getElementById()):
    var appendTo = document.getElementById(settings.container),
        fragment = document.createDocumentFragment(),

        // 'button' is perhaps a misnomer, since we're creating
        // whatever element the user defined, with the
        // settings.elements property:
        button = document.createElement(settings.elements),
        br = document.createElement('br'),
        clone;

    // if there is a class-name set for the created elements,
    // we set that on the created-element (which will be
    // copied to all clones, in the loop):
    if (settings.elementClass) {
        button.classList.add(settings.elementClass);
    }

    // if the settings.height property is not 'equal', and
    // the settings.height can be parsed as a number (a
    // naive check, and we're not validating units):
    if (settings.height !== 'equal' && parseFloat(settings.height)) {

        // we set the height of the created element to
        // the value of the settings.height property:
        button.style.height = settings.height;
    }
    // As above, but for height:
    if (settings.width !== 'equal' && parseFloat(settings.width)) {
        button.style.width = settings.width;
    }

    // iterating from 0 to the result of multiplying the
    // required number of rows by the required number of columns:
    for (var i = 0, len = (settings.rows * settings.cols); i < len; i++) {
        clone = button.cloneNode();
        clone.textContent = i;
        fragment.appendChild(clone);
        if ((i + 1) % settings.cols === 0) {
            fragment.appendChild(br.cloneNode())
        }
    }
    appendTo.appendChild(fragment);

    // To avoid running the same test, in subsequent
    // if assessments, we create a couple of Booleans
    // to test whether settings.width, or
    // settings.height, were set to the string 'equal':
    var widthEqual = settings.width === 'equal',
        heightEqual = settings.height === 'equal';

    // if either of those assessments returned true:
    if (widthEqual || heightEqual) {

        // we find all the elements contained within the
        // appended node (to which the elements were
        // appended) that have the tagName of the
        // created elements:
        var appended = appendTo.getElementsByTagName(settings.elements),

            // we get the width, and height, of the last
            // of those elements - on the assumption that
            // that element will have the highest, and
            // therefore longest/largest number:
            width = appended[appended.length - 1].clientWidth,
            height = appended[appended.length - 1].clientHeight;

        // if both settings.width and settings.height were
        // set to 'equal':
        if (widthEqual && heightEqual) {

            // we use Function.prototype.call(), to apply
            // Array.prototype.forEach() to the Array-like
            // NodeList returned by document.getElementsByTagName()
            // (from earlier):
            Array.prototype.forEach.call(appended, function (btn) {
                // btn - the first (and, here, only) argument
                // to the anonymous function is the array-
                // element over which we're iterating:

                // setting the width and height of the
                // current element to be equal to the
                // found width/height of the last
                // element:
                btn.style.width = width + 'px';
                btn.style.height = height + 'px';
            });

        // otherwise, if only the width was 'equal':
        } else if (widthEqual) {

            // As above, setting only the width:
            Array.prototype.forEach.call(appended, function (btn) {
                btn.style.width = width + 'px';
            });

        // As above, addressing only the height:
        } else if (heightEqual) {

            Array.prototype.forEach.call(appended, function (btn) {
                btn.style.height = height + 'px';
            });
        }
    }
}

// calling the function, using only the defaults:
mynumber();

// calling the function, setting
// custom values:
mynumber({
    'container' : 'anotherElement',
    'rows' : 5,
    'cols': 4,
    'elementClass': 'arbitraryClassName'
});

// calling the function, this time
// explicitly setting the height
// and width:
mynumber({
    'container' : 'more',
    'elements' : 'span',
    'width' : '3em',
    'height' : '2em'
});

function mynumber(opts) {
  var settings = {
    'container': 'btnsize',
    'elements': 'button',
    'elementClass': 'newButton',
    'height': 'equal',
    'width': 'equal',
    'rows': 3,
    'cols': 3
  };
  for (var property in opts) {
    if (opts.hasOwnProperty(property)) {
      settings[property] = opts[property];
    }
  }
  var appendTo = document.getElementById(settings.container),
    fragment = document.createDocumentFragment(),
    button = document.createElement(settings.elements),
    br = document.createElement('br'),
    clone;
  if (settings.elementClass) {
    button.classList.add(settings.elementClass);
  }
  if (settings.height !== 'equal' && parseFloat(settings.height)) {
    button.style.height = settings.height;
  }
  if (settings.width !== 'equal' && parseFloat(settings.width)) {
    button.style.width = settings.width;
  }

  for (var i = 0, len = (settings.rows * settings.cols); i < len; i++) {
    clone = button.cloneNode();
    clone.textContent = i;
    fragment.appendChild(clone);
    if ((i + 1) % settings.cols === 0) {
      fragment.appendChild(br.cloneNode())
    }
  }
  appendTo.appendChild(fragment);

  var widthEqual = settings.width === 'equal',
    heightEqual = settings.height === 'equal';

  if (widthEqual || heightEqual) {
    var appended = appendTo.getElementsByTagName(settings.elements),
      width = appended[appended.length - 1].clientWidth,
      height = appended[appended.length - 1].clientHeight;

    if (widthEqual && heightEqual) {

      Array.prototype.forEach.call(appended, function(btn) {
        btn.style.width = width + 'px';
        btn.style.height = height + 'px';
      });
    } else if (widthEqual) {

      Array.prototype.forEach.call(appended, function(btn) {
        btn.style.width = width + 'px';
      });

    } else if (heightEqual) {

      Array.prototype.forEach.call(appended, function(btn) {
        btn.style.height = height + 'px';
      });
    }
  }
}

mynumber();
mynumber({
  'container': 'anotherElement',
  'rows': 5,
  'cols': 4,
  'elementClass': 'arbitraryClassName'
});
mynumber({
  'container': 'more',
  'width': '3em',
  'height': '2em'
});
button {
  font-size: 2em;
}
.arbitraryClassName {
  color: #fff;
  border: 1px solid limegreen;
  text-shadow: 0 0 2px #000;
}
<div id="btnsize"></div>
<div id="anotherElement"></div>
<div id="more"></div>

外部JS Fiddle demo,用于实验/开发。

现在,为了尽可能简单地解决您的问题,使用您最初发布的代码(顺便说一句,在JavaScript中,#字符 对注释无效;它是一种语法错误:Uncaught SyntaxError: Unexpected token ILLEGAL),您可以简单地使用CSS,如下所示:

function mynumber() {
  var i, j = 1,
    num = 0; // i used for making three buttons in row and j used for repeat same process no of time and num is int text on button
  do {
    for (i = 1; i <= 3; i++) {
      var btn = document.createElement("BUTTON"); // create button using javascript
      var txt = document.createTextNode(num++); // creat text on button
      btn.appendChild(txt); // attached text on button
      document.getElementById("btnsize").appendChild(btn); // atache button with text in div 
    }
    var next = document.createElement("BR");
    document.getElementById("btnsize").appendChild(next);
    j++;
  }
  while (j < 4)
}

mynumber();
button {
  width: 3em;
  height: 4em;
}
<div id="btnsize"></div>

外部JS Fiddle demo

这个CSS当然匹配页面中的所有<button>元素;但是,您可以将选择器修改为仅对<button>元素中的btnsize个元素更具体:

#btnsize button {
  width: 3em;
  height: 2em;
  color: #f00;
}

function mynumber() {
  var i, j = 1,
    num = 0; // i used for making three buttons in row and j used for repeat same process no of time and num is int text on button
  do {
    for (i = 1; i <= 3; i++) {
      var btn = document.createElement("BUTTON"); // create button using javascript
      var txt = document.createTextNode(num++); // creat text on button
      btn.appendChild(txt); // attached text on button
      document.getElementById("btnsize").appendChild(btn); // atache button with text in div 
    }
    var next = document.createElement("BR");
    document.getElementById("btnsize").appendChild(next);
    j++;
  }
  while (j < 4)
}

mynumber();
#btnsize button {
  width: 3em;
  height: 4em;
  color: #f00;
}
<div id="btnsize"></div>
<button>Just to demonstrate that I'm not being styled</button>

外部JS Fiddle demo

或者您可以在创建<button>元素时添加类名:

#btnsize button {
  width: 3em;
  height: 2em;
  color: #f00;
}

function mynumber() {
  var i, j = 1,
    num = 0; // i used for making three buttons in row and j used for repeat same process no of time and num is int text on button
  do {
    for (i = 1; i <= 3; i++) {
      var btn = document.createElement("BUTTON"); // create button using javascript
      
      // adding a class-name:
      btn.classList.add('buttonClassName');
      
      var txt = document.createTextNode(num++); // creat text on button
      btn.appendChild(txt); // attached text on button
      document.getElementById("btnsize").appendChild(btn); // atache button with text in div 
    }
    var next = document.createElement("BR");
    document.getElementById("btnsize").appendChild(next);
    j++;
  }
  while (j < 4)
}

mynumber();
.buttonClassName {
  width: 3em;
  height: 4em;
  color: #f00;
}
<div id="btnsize"></div>
<button>Just to demonstrate that I'm not being styled</button>

外部JS Fiddle demo

参考文献: