最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I pass a custom attribute to a function? - Stack Overflow

programmeradmin0浏览0评论
<select data-myattr="123" id="cboTest" 
        onchange="SayHello(this.data-myattr)">

This doesn't work. If I take the data-off of it it, it works, but from what I've read, it is html5 safe to do it that way. However, doing it that way, I get: "Microsoft JScript runtime error: 'myattr' is undefined".

This is my super-complex function:

function SayHello(msg) {
    alert(msg);
}

Thanks in advance.

<select data-myattr="123" id="cboTest" 
        onchange="SayHello(this.data-myattr)">

This doesn't work. If I take the data-off of it it, it works, but from what I've read, it is html5 safe to do it that way. However, doing it that way, I get: "Microsoft JScript runtime error: 'myattr' is undefined".

This is my super-complex function:

function SayHello(msg) {
    alert(msg);
}

Thanks in advance.

Share Improve this question edited Feb 1, 2015 at 16:38 Deduplicator 45.7k7 gold badges72 silver badges123 bronze badges asked Jul 24, 2012 at 17:11 YatrixYatrix 13.8k17 gold badges54 silver badges82 bronze badges 7
  • 4 this.dataset.myattr (won't work in "shitty" browsers) – Šime Vidas Commented Jul 24, 2012 at 17:13
  • 1 You probably meant legacy browsers. – Frédéric Hamidi Commented Jul 24, 2012 at 17:15
  • 2 @FrédéricHamidi Yea, that would be the appropriate term :) – Šime Vidas Commented Jul 24, 2012 at 17:17
  • They don't call them "shitty" in the biz? Hehe. – Yatrix Commented Jul 24, 2012 at 17:17
  • 1 @Yatrix, sometimes we have to support them. Calling them names only lowers morale and doesn't achieve much, calling them legacy conveys more of a sense of positive, backwards compatibility effort instead. – Frédéric Hamidi Commented Jul 24, 2012 at 17:20
 |  Show 2 more comments

3 Answers 3

Reset to default 15

Try like this:

<select data-myattr="123" id="cboTest" 
        onchange="SayHello(this.getAttribute('data-myattr'))">

The expression:

onchange="SayHello(this.data-myattr)">

Is being interpretted as this.data minus myattr. You'd have to use:

onchange="SayHello(this.getAttribute('data-myattr'))"

instead.

Something like getAttribute() should do

Here's an example:

<select data-myattr="123" id="cboTest" 
onchange="SayHello(this.getAttribute('data-myattr'))">
    <option>1</option>
    <option>2</option>
</select>

Also, I'd try avoiding the use of inline scripts since they make HTML messy. Use addEventListener/attachEvent (older IE) instead.

发布评论

评论列表(0)

  1. 暂无评论