开发者

Using javascript to check if a HTML table cell is empty?

Is these some simple JS code t开发者_StackOverflow社区hat allows me to check whether a cell is empty.

I am trying to code a function that is called using "onmouseover=func()"; I just cant seem to get the JS code right. Any ideas?

What im ideally trying to work toward is a code that can detemine whether a cell is empty and if so, place a simple value in, like "Cell Empty".

I know it probably sounds simple but i could use a little help. Thanks for any ideas.


It depends a little on what will be in there initially. In my experience, tables behave strangely if a cell contains only whitespace, and so a common workaround is to put a   in there to stop it collapsing. Anyway, here's how you'd check:

function elementIsEmpty(el) {
    return (/^(\s| )*$/.test(el.innerHTML);
}

function replaceCell(td) {
    if (elementIsEmpty(td)) {
        td.innerHTML = 'Cell Empty';
    }
}


<td onmouseover="replaceCell(this)"></td>

... though a better way would be to apply the behaviours through Javascript event handlers.


If you're using jQuery, use the html() method on the element. Given this markup:

<td id="my_cell"></td>

This code will do it:

if ($('#my_cell').html() == '') {
  $('#my_cell').html('Cell Empty');
}


Withouth jQuery (like in the old good times):

function func(e){
    var target = window.event ? window.event.srcElement : e ? e.target : null;
    if (target.innerHTML === ''){
        target.innerHTML = 'Cell Empty!';
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜