将一个类添加到表行onclick

时间:2011-09-04 16:54:49

标签: javascript html5

我想将一个类添加到表行onclick:

<tr class="gradeA " onclick="window.location.href='games/BG-1001.php'; obj.className='diagram-popup';" >

...

<!--Another Pop-up for diagram-->
<script src="js/jquery.popupWindow-min.js" ></script> 
<script>
    $('.diagram-popup').popupWindow({centerBrowser:1, height:560, width:1024});
</script>

我该怎么做? obj.className='diagram-popup';语法似乎有误。

3 个答案:

答案 0 :(得分:0)

要具体回答您的问题,请在该上下文中使用this

<table>
    <tr onclick="this.className='test';alert(this.className);">
        <td>Click me (I will replace the className)</td>
    </tr>
    <tr onclick="this.className+=' test';alert(this.className);">
        <td>Click me to add (I will add to the className, click more than once)</td>
    </tr>
    <tr class="test">
        <td>Click me for jQuery handler (I will only add classes once when clicked more than once)</td>
    </tr>
</table>

$('.test').click(function(){
    $(this).addClass('test'); // Note, will not add the same class more than once
    alert(this.className);
});

http://jsfiddle.net/userdude/NBU8L/

如果你正在使用jQuery,我会避开内联处理程序并使用jQuery的处理程序:

$('.gradeA').click(function(){
    $(this).addClass('diagram-popup')
           .popupWindow({
               centerBrowser:1,
               height:560,
               width:1024
           });
});

答案 1 :(得分:0)

为什么要使用这么多并发症?

使用jQuery提供关键字this

你可以这样使用:

<tr class="add">Some thing</tr>

和jquery一样:

$('.add').click(function() {
$(this).addClass('addedclass');
})

答案 2 :(得分:0)

您可以利用Element Web APIevent delegation(来管理事件处理)来轻松地做到这一点。您需要注意下面的代码中handleClick的工作方式(其他大多数代码只是为了展示如何使用Web API来设置表格,而不是编写HTML)-注释很容易解释,但如果您还有其他问题,请联系lmk:

// Reference to our table DOM element
const tableEl = document.querySelector('#tableEl');

// Style class we want to add to clicked rows
const cls = "foo";

// Function to generate a single tr element to add to our table
const generateTrEl = i => {
  const trEl = document.createElement('tr'); // Create a tr
  const tdEl = document.createElement('td'); // Create a td to go inside tr
  trEl.setAttribute('class', 'gradeA'); // Add the specified attribute
  tdEl.setAttribute('colspan', '1'); // Set the colspan to stretch whole table
  tdEl.insertAdjacentText('afterbegin', i); // Insert the text in the td
  trEl.insertAdjacentElement('beforeend', tdEl); // Insert the td in the tr

  return trEl;
};

// Event handling function that takes advantage of event delegation (so we don't have to manage multiple listners in our code)
const handleClick = e => {
  if (e.target.tagName === 'TD') {
    e.target.classList.add(cls);
  }
};

// Setup the table for testing functionality 
const init = () => {
  for (let i = 0; i < 10; i += 1) {
    tableEl.appendChild(generateTrEl(i));
  }

  tableEl.addEventListener('click', handleClick);
};

init();
.foo {
  background-color: yellow;
}
<table id="tableEl" border="1" width="300px"></table>