获得个人阶级和价值

时间:2014-07-11 23:56:44

标签: javascript jquery html css

我在jsFiddle上制作了一个没有插件的键盘。我将每个按钮作为单独的元素,但为了使我的$().append()函数能够工作,我需要在少量代码中单击该按钮的类值。我能想到的唯一方法是为每个按钮创建一个变量,并为每个按钮创建一个$().click()函数。

HTML:

<button class='q'>Q</button><button class='w'>W</button><button class='e'>E</button>        <button class='r'>R</button><button class='t'>T</button><button class='y'>Y</button><button class='u'>U</button><button class='i'>I</button><button class='o'>O</button><button class='p'>P</button><br />
<button style='margin-left: 23px;' class='a'>A</button><button class='s'>S</button><button class='d'>D</button><button class='f'>F</button><button class='g'>G</button><button class='h'>H</button><button class='j'>J</button><button class='k'>K</button><button class='l'>L</button><br />
<button style='margin-left: 70px;' class='z'>Z</button><button class='x'>X</button><button class='c'>C</button><button class='v'>V</button><button class='b'>B</button><button class='n'>N</button><button class='m'>M</button>
<br />
<br />
<h1></h1>

CSS:

body: {
  text-align: center
}
button {
  width: 40px;
  height: 40px;
  background: white;
  border: 2px solid #6699ff;
  border-radius: 10px;
  color: #6699ff;
  transition: 0.1s linear;
  margin: 3px;
}
button:hover {
  border: 2px solid #5c8ae6;
  color: #5c8ae6
}
button:active{
  border: 2px solid #5c8ae6;
  background: #5c8ae6;
  color: white;
}
button:focus {
  outline: 0
}

2 个答案:

答案 0 :(得分:4)

获取每个按钮的字母......

试试这个:

$(document).ready(function() {
     $('button').click(function() {
          //alert($(this).html());
          $('h1').append(this.textContent);
     });
});

<强> JSFiddle

答案 1 :(得分:0)

将按钮包裹在div中

<div class="buttons">
    <button class='q'>Q</button><button class='w'>W</button><button class='e'>E</button><button class='r'>R</button><button class='t'>T</button><button class='y'>Y</button><button class='u'>U</button><button class='i'>I</button><button class='o'>O</button><button class='p'>P</button><br />
    <button style='margin-left: 23px;' class='a'>A</button><button class='s'>S</button><button class='d'>D</button><button class='f'>F</button><button class='g'>G</button><button class='h'>H</button><button class='j'>J</button><button class='k'>K</button><button class='l'>L</button><br /><button style='margin-left: 70px;' class='z'>Z</button><button class='x'>X</button><button class='c'>C</button><button class='v'>V</button><button class='b'>B</button><button class='n'>N</button><button class='m'>M</button>
</div>
<br />
<br />
<h1></h1>
<div class="output"></div>

然后使用on

$(function(){
    $(".buttons").on("click", "button", function(e){
        $(".output").append(this.className);
        // Or text()
        // $(".output").append($(this).text());
    });
});

JSFiddle