开发者

jQuery - Change part of contents in form

Just starting out with jQuery and this problem seems to be impossible to me. Search all the forums, no luck. Maybe you guys can help me?

My html looks kinda like this:

<form>
   <table class="tableClassName"> 
     [content]
   </table>
   <div class="divClassName"> 
     [content]
   </div>
Here is some text
   <div class="divClassName"> 
     [content]
   </div>
</form>

The form has a buch of child elements. I only want to chance the text "here i som text", to something else. Is there some way i can leave all the child elements a开发者_StackOverflow中文版nd only change this particular text?

Here is my noob code, so far:

$(document).ready(function() {
var oldText = "Here is some text";
var newText = "the new text";
var entireElement = $("form:contains(" + oldText + "):not(table, div)").html();
$("form:contains(" + oldText + "):not(table, div)").html(entireElement+newText); 
});

As you can see this replaces nothing. It only puts my new text just before my </form>. What to do?


If you don't know where your text node is within the container, you might do something like this, i.e., loop over all of them until you get a match:

​$("form").contents().each(function() {
    if(this.nodeType == 3) {
        if($.trim(this.nodeValue) == 'Here is some text') {
            this.nodeValue = 'New text';   
        }
    }
});​​​​​

Demo: http://jsfiddle.net/8yAbu/


Make things simpler to yourself. Use ID's! ;)

New HTML code

<form>
    <table class="tableClassName">[content]</table>
    <div class="divClassName">[content]</div>
    <span id="form_text">Here is some text</span>
</form>

New Javascript Code

$(document).ready(function() {
    var newText = "the new text";
    $('#form_text').html(newText); 
});


Give this a shot:

$(document).ready(function() { 

  var oldText = "Here is some text"; 
  var newText = "the new text"; 
  var newHtml = $("form:contains(" + oldText + "):not(table, div)").html().replace(oldText,newText);
  $("form:contains(" + oldText + "):not(table, div)").html(newHtml);  

}); 

p.s. This is definitely not the most optimized way to accomplish it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜