简体   繁体   English

如何使用jQuery替换textarea内部属性的内容?

[英]How can I use jQuery to replace the content of an attribute inside of a textarea?

I have this code: 我有以下代码:

<textarea class="mapCode">
<    area shape="rect" coords="" href="http://www.sitehere" target="_self">
</textarea>

How can I use jQuery to insert/update values into the coords attribute even if it's not empty? 即使它不为空,我如何使用jQuery将值插入/更新到coords属性中?

Right now I'm using... 现在我正在使用...

return $(this).text().replace("coords=\"\"", 'coords="'+selection.x1+','+selection.y1+','+selection.x2+','+selection.y2+'"');

But of course that only works one time since it's always looking for an empty coords="" attribute. 但是,由于它一直在寻找一个空的coords=""属性,因此当然只能使用一次。

You should use a regular expression with a wildcard in your replace call: 您应该在替换调用中使用带通配符的正则表达式:

$(this).text().replace(/coords=".*"/gi, 'coords="..."');

This will work with both an empty and a set coords attribute. 这将同时使用empty和set coords属性。

You can wrap textarea content in a jQuery object then use any relevant method to update it, eg: 您可以将textarea内容包装在jQuery对象中,然后使用任何相关方法对其进行更新,例如:

var $content = $('<div/>').html($('.mapCode').val());
$content.find('area').attr('coords', selection.x1+','+selection.y1+','+selection.x2+','+selection.y2);

$('.mapCode').val($content.html());

-DEMO- -演示-

<textarea class="mapCode">
   <area id="myArea" shape="rect" coords="" href="http://www.sitehere" target="_self">
</textarea>

JavaScript: JavaScript的:

$(function () {
    var myArea = $('#myArea');
    myArea.attr('coords', selection.x1+','+selection.y1+','+selection.x2+','+selection.y2);

});​

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM