0

我有这个代码:

$('#output').html("<strong>id:</strong>"+id);

然后

<div id="output">this element will be accessed by jquery and this text replaced</div>

以上工作正常,但我需要的是输出进入警报所以....

<a href="#" onclick="alert('OUTPUT GOES HERE')">Alert Me</a>  <- See here

如何才能做到这一点?

4

3 回答 3

1

给锚点某种id可用于查找的类型或属性:

<a href="#" id="alertOutput">Alert Me</a>

然后绑定到它的点击事件来提醒元素的文本内容#output

$("#alertOutput").on("click", function(e){
    e.preventDefault();
    alert( $("#output").text() );
});

e.preventDefault()部分将防止在单击锚点时页面跳回文档顶部。

于 2012-11-19T15:51:17.743 回答
1

不确定我是否完全理解您的要求,绑定点击事件而不是onclick属性。

HTML:

<a href="#" id="alertAnchor">Alert Me</a>

JavaScript:

$('#alertAnchor').on('click', function(e) {
    e.preventDefault();
    alert($('#output').text());
});

希望这会有所帮助,如果你澄清你在找什么我可以编辑。

于 2012-11-19T15:51:52.647 回答
1

或者如果你很懒,想要快速修复:

<a href="#" onclick="e.preventDefault(); alert($('#output').html())">Alert Me</a>  <- See here
于 2012-11-19T15:56:48.607 回答